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::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, 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 {
4029 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4031 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4032 assert_eq!(reestablish_1.len(), 1);
4033 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4034 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4036 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4037 assert_eq!(reestablish_2.len(), 1);
4039 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4040 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4041 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4042 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4044 assert!(as_resp.0.is_none());
4045 assert!(bs_resp.0.is_none());
4047 assert!(bs_resp.1.is_none());
4048 assert!(bs_resp.2.is_none());
4050 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4052 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4053 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4054 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4055 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4056 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4057 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4058 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4059 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4060 // No commitment_signed so get_event_msg's assert(len == 1) passes
4061 check_added_monitors!(nodes[1], 1);
4063 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4064 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4065 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4066 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4067 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4068 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4069 assert!(bs_second_commitment_signed.update_fee.is_none());
4070 check_added_monitors!(nodes[1], 1);
4072 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4073 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4074 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4075 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4076 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4077 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4078 assert!(as_commitment_signed.update_fee.is_none());
4079 check_added_monitors!(nodes[0], 1);
4081 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4082 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4083 // No commitment_signed so get_event_msg's assert(len == 1) passes
4084 check_added_monitors!(nodes[0], 1);
4086 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4087 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4088 // No commitment_signed so get_event_msg's assert(len == 1) passes
4089 check_added_monitors!(nodes[1], 1);
4091 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4092 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4093 check_added_monitors!(nodes[1], 1);
4095 expect_pending_htlcs_forwardable!(nodes[1]);
4097 let events_5 = nodes[1].node.get_and_clear_pending_events();
4098 assert_eq!(events_5.len(), 1);
4100 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4101 assert_eq!(payment_hash_2, *payment_hash);
4103 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4104 assert!(payment_preimage.is_none());
4105 assert_eq!(payment_secret_2, *payment_secret);
4107 _ => panic!("expected PaymentPurpose::InvoicePayment")
4110 _ => panic!("Unexpected event"),
4113 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4114 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4115 check_added_monitors!(nodes[0], 1);
4117 expect_payment_path_successful!(nodes[0]);
4118 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4121 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4122 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4123 // to avoid our counterparty failing the channel.
4124 let chanmon_cfgs = create_chanmon_cfgs(2);
4125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4127 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4129 create_announced_chan_between_nodes(&nodes, 0, 1);
4131 let our_payment_hash = if send_partial_mpp {
4132 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4133 // Use the utility function send_payment_along_path to send the payment with MPP data which
4134 // indicates there are more HTLCs coming.
4135 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.
4136 let payment_id = PaymentId([42; 32]);
4137 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4138 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4139 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4140 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4141 &None, session_privs[0]).unwrap();
4142 check_added_monitors!(nodes[0], 1);
4143 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4144 assert_eq!(events.len(), 1);
4145 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4146 // hop should *not* yet generate any PaymentClaimable event(s).
4147 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4150 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4153 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4154 connect_block(&nodes[0], &block);
4155 connect_block(&nodes[1], &block);
4156 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4157 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4158 block.header.prev_blockhash = block.block_hash();
4159 connect_block(&nodes[0], &block);
4160 connect_block(&nodes[1], &block);
4163 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4165 check_added_monitors!(nodes[1], 1);
4166 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4167 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4168 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4169 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4170 assert!(htlc_timeout_updates.update_fee.is_none());
4172 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4173 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4174 // 100_000 msat as u64, followed by the height at which we failed back above
4175 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4176 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4177 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4181 fn test_htlc_timeout() {
4182 do_test_htlc_timeout(true);
4183 do_test_htlc_timeout(false);
4186 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4187 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4188 let chanmon_cfgs = create_chanmon_cfgs(3);
4189 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4190 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4191 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4192 create_announced_chan_between_nodes(&nodes, 0, 1);
4193 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4195 // Make sure all nodes are at the same starting height
4196 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4197 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4198 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4200 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4201 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4202 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4203 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4204 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4205 check_added_monitors!(nodes[1], 1);
4207 // Now attempt to route a second payment, which should be placed in the holding cell
4208 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4209 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4210 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4211 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4213 check_added_monitors!(nodes[0], 1);
4214 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4215 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4216 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4217 expect_pending_htlcs_forwardable!(nodes[1]);
4219 check_added_monitors!(nodes[1], 0);
4221 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4222 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4223 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4224 connect_blocks(&nodes[1], 1);
4227 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 }]);
4228 check_added_monitors!(nodes[1], 1);
4229 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4230 assert_eq!(fail_commit.len(), 1);
4231 match fail_commit[0] {
4232 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4233 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4234 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4236 _ => unreachable!(),
4238 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4240 expect_payment_failed!(nodes[1], second_payment_hash, false);
4245 fn test_holding_cell_htlc_add_timeouts() {
4246 do_test_holding_cell_htlc_add_timeouts(false);
4247 do_test_holding_cell_htlc_add_timeouts(true);
4250 macro_rules! check_spendable_outputs {
4251 ($node: expr, $keysinterface: expr) => {
4253 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4254 let mut txn = Vec::new();
4255 let mut all_outputs = Vec::new();
4256 let secp_ctx = Secp256k1::new();
4257 for event in events.drain(..) {
4259 Event::SpendableOutputs { mut outputs } => {
4260 for outp in outputs.drain(..) {
4261 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());
4262 all_outputs.push(outp);
4265 _ => panic!("Unexpected event"),
4268 if all_outputs.len() > 1 {
4269 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) {
4279 fn test_claim_sizeable_push_msat() {
4280 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4281 let chanmon_cfgs = create_chanmon_cfgs(2);
4282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4284 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4286 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4287 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4288 check_closed_broadcast!(nodes[1], true);
4289 check_added_monitors!(nodes[1], 1);
4290 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4291 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4292 assert_eq!(node_txn.len(), 1);
4293 check_spends!(node_txn[0], chan.3);
4294 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
4296 mine_transaction(&nodes[1], &node_txn[0]);
4297 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4299 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4300 assert_eq!(spend_txn.len(), 1);
4301 assert_eq!(spend_txn[0].input.len(), 1);
4302 check_spends!(spend_txn[0], node_txn[0]);
4303 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4307 fn test_claim_on_remote_sizeable_push_msat() {
4308 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4309 // to_remote output is encumbered by a P2WPKH
4310 let chanmon_cfgs = create_chanmon_cfgs(2);
4311 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4312 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4313 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4315 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4316 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4317 check_closed_broadcast!(nodes[0], true);
4318 check_added_monitors!(nodes[0], 1);
4319 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4321 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4322 assert_eq!(node_txn.len(), 1);
4323 check_spends!(node_txn[0], chan.3);
4324 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
4326 mine_transaction(&nodes[1], &node_txn[0]);
4327 check_closed_broadcast!(nodes[1], true);
4328 check_added_monitors!(nodes[1], 1);
4329 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4330 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4332 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4333 assert_eq!(spend_txn.len(), 1);
4334 check_spends!(spend_txn[0], node_txn[0]);
4338 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4339 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4340 // to_remote output is encumbered by a P2WPKH
4342 let chanmon_cfgs = create_chanmon_cfgs(2);
4343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4345 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4347 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4348 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4349 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4350 assert_eq!(revoked_local_txn[0].input.len(), 1);
4351 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4353 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4354 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4355 check_closed_broadcast!(nodes[1], true);
4356 check_added_monitors!(nodes[1], 1);
4357 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4359 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4360 mine_transaction(&nodes[1], &node_txn[0]);
4361 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4363 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4364 assert_eq!(spend_txn.len(), 3);
4365 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4366 check_spends!(spend_txn[1], node_txn[0]);
4367 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4371 fn test_static_spendable_outputs_preimage_tx() {
4372 let chanmon_cfgs = create_chanmon_cfgs(2);
4373 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4374 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4375 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4377 // Create some initial channels
4378 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4380 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4382 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4383 assert_eq!(commitment_tx[0].input.len(), 1);
4384 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4386 // Settle A's commitment tx on B's chain
4387 nodes[1].node.claim_funds(payment_preimage);
4388 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4389 check_added_monitors!(nodes[1], 1);
4390 mine_transaction(&nodes[1], &commitment_tx[0]);
4391 check_added_monitors!(nodes[1], 1);
4392 let events = nodes[1].node.get_and_clear_pending_msg_events();
4394 MessageSendEvent::UpdateHTLCs { .. } => {},
4395 _ => panic!("Unexpected event"),
4398 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4399 _ => panic!("Unexepected event"),
4402 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4403 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4404 assert_eq!(node_txn.len(), 1);
4405 check_spends!(node_txn[0], commitment_tx[0]);
4406 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4408 mine_transaction(&nodes[1], &node_txn[0]);
4409 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4410 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4412 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4413 assert_eq!(spend_txn.len(), 1);
4414 check_spends!(spend_txn[0], node_txn[0]);
4418 fn test_static_spendable_outputs_timeout_tx() {
4419 let chanmon_cfgs = create_chanmon_cfgs(2);
4420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4422 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4424 // Create some initial channels
4425 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4427 // Rebalance the network a bit by relaying one payment through all the channels ...
4428 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4430 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4432 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4433 assert_eq!(commitment_tx[0].input.len(), 1);
4434 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4436 // Settle A's commitment tx on B' chain
4437 mine_transaction(&nodes[1], &commitment_tx[0]);
4438 check_added_monitors!(nodes[1], 1);
4439 let events = nodes[1].node.get_and_clear_pending_msg_events();
4441 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4442 _ => panic!("Unexpected event"),
4444 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4446 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4447 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4448 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4449 check_spends!(node_txn[0], commitment_tx[0].clone());
4450 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4452 mine_transaction(&nodes[1], &node_txn[0]);
4453 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4454 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4455 expect_payment_failed!(nodes[1], our_payment_hash, false);
4457 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4458 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4459 check_spends!(spend_txn[0], commitment_tx[0]);
4460 check_spends!(spend_txn[1], node_txn[0]);
4461 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4465 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4466 let chanmon_cfgs = create_chanmon_cfgs(2);
4467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4471 // Create some initial channels
4472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4474 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4475 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4476 assert_eq!(revoked_local_txn[0].input.len(), 1);
4477 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4479 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4481 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4482 check_closed_broadcast!(nodes[1], true);
4483 check_added_monitors!(nodes[1], 1);
4484 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4486 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4487 assert_eq!(node_txn.len(), 1);
4488 assert_eq!(node_txn[0].input.len(), 2);
4489 check_spends!(node_txn[0], revoked_local_txn[0]);
4491 mine_transaction(&nodes[1], &node_txn[0]);
4492 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4494 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4495 assert_eq!(spend_txn.len(), 1);
4496 check_spends!(spend_txn[0], node_txn[0]);
4500 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4501 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4502 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4507 // Create some initial channels
4508 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4510 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4511 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4512 assert_eq!(revoked_local_txn[0].input.len(), 1);
4513 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4515 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4517 // A will generate HTLC-Timeout from revoked commitment tx
4518 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4519 check_closed_broadcast!(nodes[0], true);
4520 check_added_monitors!(nodes[0], 1);
4521 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4522 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4524 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4525 assert_eq!(revoked_htlc_txn.len(), 1);
4526 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4527 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4528 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4529 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4531 // B will generate justice tx from A's revoked commitment/HTLC tx
4532 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4533 check_closed_broadcast!(nodes[1], true);
4534 check_added_monitors!(nodes[1], 1);
4535 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4537 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4538 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4539 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4540 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4541 // transactions next...
4542 assert_eq!(node_txn[0].input.len(), 3);
4543 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4545 assert_eq!(node_txn[1].input.len(), 2);
4546 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4547 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4548 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4550 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4551 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4554 mine_transaction(&nodes[1], &node_txn[1]);
4555 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4557 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4558 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4559 assert_eq!(spend_txn.len(), 1);
4560 assert_eq!(spend_txn[0].input.len(), 1);
4561 check_spends!(spend_txn[0], node_txn[1]);
4565 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4566 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4567 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4570 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4572 // Create some initial channels
4573 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4575 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4576 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4577 assert_eq!(revoked_local_txn[0].input.len(), 1);
4578 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4580 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4581 assert_eq!(revoked_local_txn[0].output.len(), 2);
4583 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4585 // B will generate HTLC-Success from revoked commitment tx
4586 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4587 check_closed_broadcast!(nodes[1], true);
4588 check_added_monitors!(nodes[1], 1);
4589 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4590 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4592 assert_eq!(revoked_htlc_txn.len(), 1);
4593 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4594 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4595 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4597 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4598 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4599 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4601 // A will generate justice tx from B's revoked commitment/HTLC tx
4602 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4603 check_closed_broadcast!(nodes[0], true);
4604 check_added_monitors!(nodes[0], 1);
4605 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4607 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4608 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4610 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4611 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4612 // transactions next...
4613 assert_eq!(node_txn[0].input.len(), 2);
4614 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4615 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4616 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4618 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4619 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4622 assert_eq!(node_txn[1].input.len(), 1);
4623 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4625 mine_transaction(&nodes[0], &node_txn[1]);
4626 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4628 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4629 // didn't try to generate any new transactions.
4631 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4632 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4633 assert_eq!(spend_txn.len(), 3);
4634 assert_eq!(spend_txn[0].input.len(), 1);
4635 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4636 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4637 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4638 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4642 fn test_onchain_to_onchain_claim() {
4643 // Test that in case of channel closure, we detect the state of output and claim HTLC
4644 // on downstream peer's remote commitment tx.
4645 // First, have C claim an HTLC against its own latest commitment transaction.
4646 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4648 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4651 let chanmon_cfgs = create_chanmon_cfgs(3);
4652 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4653 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4654 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4656 // Create some initial channels
4657 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4658 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4660 // Ensure all nodes are at the same height
4661 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4662 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4663 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4664 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4666 // Rebalance the network a bit by relaying one payment through all the channels ...
4667 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4668 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4670 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4671 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4672 check_spends!(commitment_tx[0], chan_2.3);
4673 nodes[2].node.claim_funds(payment_preimage);
4674 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4675 check_added_monitors!(nodes[2], 1);
4676 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4677 assert!(updates.update_add_htlcs.is_empty());
4678 assert!(updates.update_fail_htlcs.is_empty());
4679 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4680 assert!(updates.update_fail_malformed_htlcs.is_empty());
4682 mine_transaction(&nodes[2], &commitment_tx[0]);
4683 check_closed_broadcast!(nodes[2], true);
4684 check_added_monitors!(nodes[2], 1);
4685 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4687 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4688 assert_eq!(c_txn.len(), 1);
4689 check_spends!(c_txn[0], commitment_tx[0]);
4690 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4691 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4692 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4694 // 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
4695 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4696 check_added_monitors!(nodes[1], 1);
4697 let events = nodes[1].node.get_and_clear_pending_events();
4698 assert_eq!(events.len(), 2);
4700 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4701 _ => panic!("Unexpected event"),
4704 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4705 assert_eq!(fee_earned_msat, Some(1000));
4706 assert_eq!(prev_channel_id, Some(chan_1.2));
4707 assert_eq!(claim_from_onchain_tx, true);
4708 assert_eq!(next_channel_id, Some(chan_2.2));
4709 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4711 _ => panic!("Unexpected event"),
4713 check_added_monitors!(nodes[1], 1);
4714 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4715 assert_eq!(msg_events.len(), 3);
4716 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4717 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4719 match nodes_2_event {
4720 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4721 _ => panic!("Unexpected event"),
4724 match nodes_0_event {
4725 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, .. } } => {
4726 assert!(update_add_htlcs.is_empty());
4727 assert!(update_fail_htlcs.is_empty());
4728 assert_eq!(update_fulfill_htlcs.len(), 1);
4729 assert!(update_fail_malformed_htlcs.is_empty());
4730 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4732 _ => panic!("Unexpected event"),
4735 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4736 match msg_events[0] {
4737 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4738 _ => panic!("Unexpected event"),
4741 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4742 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4743 mine_transaction(&nodes[1], &commitment_tx[0]);
4744 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4745 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4746 // ChannelMonitor: HTLC-Success tx
4747 assert_eq!(b_txn.len(), 1);
4748 check_spends!(b_txn[0], commitment_tx[0]);
4749 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4750 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4751 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4753 check_closed_broadcast!(nodes[1], true);
4754 check_added_monitors!(nodes[1], 1);
4758 fn test_duplicate_payment_hash_one_failure_one_success() {
4759 // Topology : A --> B --> C --> D
4760 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4761 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4762 // we forward one of the payments onwards to D.
4763 let chanmon_cfgs = create_chanmon_cfgs(4);
4764 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4765 // When this test was written, the default base fee floated based on the HTLC count.
4766 // It is now fixed, so we simply set the fee to the expected value here.
4767 let mut config = test_default_channel_config();
4768 config.channel_config.forwarding_fee_base_msat = 196;
4769 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4770 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4771 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4773 create_announced_chan_between_nodes(&nodes, 0, 1);
4774 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4775 create_announced_chan_between_nodes(&nodes, 2, 3);
4777 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4778 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4779 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4780 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4781 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4783 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4785 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4786 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4787 // script push size limit so that the below script length checks match
4788 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4789 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4790 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4791 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4792 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4794 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4795 assert_eq!(commitment_txn[0].input.len(), 1);
4796 check_spends!(commitment_txn[0], chan_2.3);
4798 mine_transaction(&nodes[1], &commitment_txn[0]);
4799 check_closed_broadcast!(nodes[1], true);
4800 check_added_monitors!(nodes[1], 1);
4801 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4802 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4804 let htlc_timeout_tx;
4805 { // Extract one of the two HTLC-Timeout transaction
4806 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4807 // ChannelMonitor: timeout tx * 2-or-3
4808 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4810 check_spends!(node_txn[0], commitment_txn[0]);
4811 assert_eq!(node_txn[0].input.len(), 1);
4812 assert_eq!(node_txn[0].output.len(), 1);
4814 if node_txn.len() > 2 {
4815 check_spends!(node_txn[1], commitment_txn[0]);
4816 assert_eq!(node_txn[1].input.len(), 1);
4817 assert_eq!(node_txn[1].output.len(), 1);
4818 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4820 check_spends!(node_txn[2], commitment_txn[0]);
4821 assert_eq!(node_txn[2].input.len(), 1);
4822 assert_eq!(node_txn[2].output.len(), 1);
4823 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4825 check_spends!(node_txn[1], commitment_txn[0]);
4826 assert_eq!(node_txn[1].input.len(), 1);
4827 assert_eq!(node_txn[1].output.len(), 1);
4828 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4831 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4832 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4834 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4835 if node_txn.len() > 2 {
4836 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4837 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4839 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4843 nodes[2].node.claim_funds(our_payment_preimage);
4844 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4846 mine_transaction(&nodes[2], &commitment_txn[0]);
4847 check_added_monitors!(nodes[2], 2);
4848 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4849 let events = nodes[2].node.get_and_clear_pending_msg_events();
4851 MessageSendEvent::UpdateHTLCs { .. } => {},
4852 _ => panic!("Unexpected event"),
4855 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4856 _ => panic!("Unexepected event"),
4858 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4859 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4860 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4861 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4862 assert_eq!(htlc_success_txn[0].input.len(), 1);
4863 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4864 assert_eq!(htlc_success_txn[1].input.len(), 1);
4865 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4866 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4867 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4869 mine_transaction(&nodes[1], &htlc_timeout_tx);
4870 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4871 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 }]);
4872 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4873 assert!(htlc_updates.update_add_htlcs.is_empty());
4874 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4875 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4876 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4877 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4878 check_added_monitors!(nodes[1], 1);
4880 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4881 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4883 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4885 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4887 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4888 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4889 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4890 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4891 assert!(updates.update_add_htlcs.is_empty());
4892 assert!(updates.update_fail_htlcs.is_empty());
4893 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4894 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4895 assert!(updates.update_fail_malformed_htlcs.is_empty());
4896 check_added_monitors!(nodes[1], 1);
4898 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4899 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4900 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4904 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4905 let chanmon_cfgs = create_chanmon_cfgs(2);
4906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4908 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4910 // Create some initial channels
4911 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4913 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4914 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4915 assert_eq!(local_txn.len(), 1);
4916 assert_eq!(local_txn[0].input.len(), 1);
4917 check_spends!(local_txn[0], chan_1.3);
4919 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4920 nodes[1].node.claim_funds(payment_preimage);
4921 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4922 check_added_monitors!(nodes[1], 1);
4924 mine_transaction(&nodes[1], &local_txn[0]);
4925 check_added_monitors!(nodes[1], 1);
4926 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4927 let events = nodes[1].node.get_and_clear_pending_msg_events();
4929 MessageSendEvent::UpdateHTLCs { .. } => {},
4930 _ => panic!("Unexpected event"),
4933 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4934 _ => panic!("Unexepected event"),
4937 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4938 assert_eq!(node_txn.len(), 1);
4939 assert_eq!(node_txn[0].input.len(), 1);
4940 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4941 check_spends!(node_txn[0], local_txn[0]);
4945 mine_transaction(&nodes[1], &node_tx);
4946 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4948 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4949 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4950 assert_eq!(spend_txn.len(), 1);
4951 assert_eq!(spend_txn[0].input.len(), 1);
4952 check_spends!(spend_txn[0], node_tx);
4953 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4956 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4957 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4958 // unrevoked commitment transaction.
4959 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4960 // a remote RAA before they could be failed backwards (and combinations thereof).
4961 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4962 // use the same payment hashes.
4963 // Thus, we use a six-node network:
4968 // And test where C fails back to A/B when D announces its latest commitment transaction
4969 let chanmon_cfgs = create_chanmon_cfgs(6);
4970 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4971 // When this test was written, the default base fee floated based on the HTLC count.
4972 // It is now fixed, so we simply set the fee to the expected value here.
4973 let mut config = test_default_channel_config();
4974 config.channel_config.forwarding_fee_base_msat = 196;
4975 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4976 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4977 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4979 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4980 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4981 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4982 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4983 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4985 // Rebalance and check output sanity...
4986 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4987 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4988 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4990 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4991 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4993 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
4995 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
4996 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4998 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
5000 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
5002 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5004 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5005 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5007 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());
5009 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());
5012 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5014 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5015 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
5018 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
5020 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5021 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());
5023 // Double-check that six of the new HTLC were added
5024 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5025 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5026 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5027 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5029 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5030 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5031 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5032 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5033 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5034 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5035 check_added_monitors!(nodes[4], 0);
5037 let failed_destinations = vec![
5038 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5039 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5040 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5041 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5043 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5044 check_added_monitors!(nodes[4], 1);
5046 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5047 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5048 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5049 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5050 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5051 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5053 // Fail 3rd below-dust and 7th above-dust HTLCs
5054 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5055 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5056 check_added_monitors!(nodes[5], 0);
5058 let failed_destinations_2 = vec![
5059 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5060 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5062 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5063 check_added_monitors!(nodes[5], 1);
5065 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5066 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5067 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5068 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5070 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5072 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5073 let failed_destinations_3 = vec![
5074 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5075 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5076 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5077 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5078 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5079 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5081 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5082 check_added_monitors!(nodes[3], 1);
5083 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5084 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5085 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5086 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5087 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5088 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5089 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5090 if deliver_last_raa {
5091 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5093 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5096 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5097 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5098 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5099 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5101 // We now broadcast the latest commitment transaction, which *should* result in failures for
5102 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5103 // the non-broadcast above-dust HTLCs.
5105 // Alternatively, we may broadcast the previous commitment transaction, which should only
5106 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5107 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5109 if announce_latest {
5110 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5112 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5114 let events = nodes[2].node.get_and_clear_pending_events();
5115 let close_event = if deliver_last_raa {
5116 assert_eq!(events.len(), 2 + 6);
5117 events.last().clone().unwrap()
5119 assert_eq!(events.len(), 1);
5120 events.last().clone().unwrap()
5123 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5124 _ => panic!("Unexpected event"),
5127 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5128 check_closed_broadcast!(nodes[2], true);
5129 if deliver_last_raa {
5130 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5132 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();
5133 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5135 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5136 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5138 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5141 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5143 check_added_monitors!(nodes[2], 3);
5145 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5146 assert_eq!(cs_msgs.len(), 2);
5147 let mut a_done = false;
5148 for msg in cs_msgs {
5150 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5151 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5152 // should be failed-backwards here.
5153 let target = if *node_id == nodes[0].node.get_our_node_id() {
5154 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5155 for htlc in &updates.update_fail_htlcs {
5156 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 });
5158 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5163 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5164 for htlc in &updates.update_fail_htlcs {
5165 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5167 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5168 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5171 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5172 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5174 if announce_latest {
5175 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5176 if *node_id == nodes[0].node.get_our_node_id() {
5177 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5180 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5182 _ => panic!("Unexpected event"),
5186 let as_events = nodes[0].node.get_and_clear_pending_events();
5187 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5188 let mut as_failds = HashSet::new();
5189 let mut as_updates = 0;
5190 for event in as_events.iter() {
5191 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5192 assert!(as_failds.insert(*payment_hash));
5193 if *payment_hash != payment_hash_2 {
5194 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5196 assert!(!payment_failed_permanently);
5198 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5201 } else if let &Event::PaymentFailed { .. } = event {
5202 } else { panic!("Unexpected event"); }
5204 assert!(as_failds.contains(&payment_hash_1));
5205 assert!(as_failds.contains(&payment_hash_2));
5206 if announce_latest {
5207 assert!(as_failds.contains(&payment_hash_3));
5208 assert!(as_failds.contains(&payment_hash_5));
5210 assert!(as_failds.contains(&payment_hash_6));
5212 let bs_events = nodes[1].node.get_and_clear_pending_events();
5213 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5214 let mut bs_failds = HashSet::new();
5215 let mut bs_updates = 0;
5216 for event in bs_events.iter() {
5217 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5218 assert!(bs_failds.insert(*payment_hash));
5219 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5220 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5222 assert!(!payment_failed_permanently);
5224 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5227 } else if let &Event::PaymentFailed { .. } = event {
5228 } else { panic!("Unexpected event"); }
5230 assert!(bs_failds.contains(&payment_hash_1));
5231 assert!(bs_failds.contains(&payment_hash_2));
5232 if announce_latest {
5233 assert!(bs_failds.contains(&payment_hash_4));
5235 assert!(bs_failds.contains(&payment_hash_5));
5237 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5238 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5239 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5240 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5241 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5242 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5246 fn test_fail_backwards_latest_remote_announce_a() {
5247 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5251 fn test_fail_backwards_latest_remote_announce_b() {
5252 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5256 fn test_fail_backwards_previous_remote_announce() {
5257 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5258 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5259 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5263 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5264 let chanmon_cfgs = create_chanmon_cfgs(2);
5265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5269 // Create some initial channels
5270 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5272 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5273 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5274 assert_eq!(local_txn[0].input.len(), 1);
5275 check_spends!(local_txn[0], chan_1.3);
5277 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5278 mine_transaction(&nodes[0], &local_txn[0]);
5279 check_closed_broadcast!(nodes[0], true);
5280 check_added_monitors!(nodes[0], 1);
5281 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5282 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5284 let htlc_timeout = {
5285 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5286 assert_eq!(node_txn.len(), 1);
5287 assert_eq!(node_txn[0].input.len(), 1);
5288 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5289 check_spends!(node_txn[0], local_txn[0]);
5293 mine_transaction(&nodes[0], &htlc_timeout);
5294 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5295 expect_payment_failed!(nodes[0], our_payment_hash, false);
5297 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5298 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5299 assert_eq!(spend_txn.len(), 3);
5300 check_spends!(spend_txn[0], local_txn[0]);
5301 assert_eq!(spend_txn[1].input.len(), 1);
5302 check_spends!(spend_txn[1], htlc_timeout);
5303 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5304 assert_eq!(spend_txn[2].input.len(), 2);
5305 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5306 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5307 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5311 fn test_key_derivation_params() {
5312 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5313 // manager rotation to test that `channel_keys_id` returned in
5314 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5315 // then derive a `delayed_payment_key`.
5317 let chanmon_cfgs = create_chanmon_cfgs(3);
5319 // We manually create the node configuration to backup the seed.
5320 let seed = [42; 32];
5321 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5322 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);
5323 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5324 let scorer = Mutex::new(test_utils::TestScorer::new());
5325 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5326 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)) };
5327 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5328 node_cfgs.remove(0);
5329 node_cfgs.insert(0, node);
5331 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5332 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5334 // Create some initial channels
5335 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5337 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5338 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5339 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5341 // Ensure all nodes are at the same height
5342 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5343 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5344 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5345 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5347 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5348 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5349 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5350 assert_eq!(local_txn_1[0].input.len(), 1);
5351 check_spends!(local_txn_1[0], chan_1.3);
5353 // We check funding pubkey are unique
5354 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]));
5355 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]));
5356 if from_0_funding_key_0 == from_1_funding_key_0
5357 || from_0_funding_key_0 == from_1_funding_key_1
5358 || from_0_funding_key_1 == from_1_funding_key_0
5359 || from_0_funding_key_1 == from_1_funding_key_1 {
5360 panic!("Funding pubkeys aren't unique");
5363 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5364 mine_transaction(&nodes[0], &local_txn_1[0]);
5365 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5366 check_closed_broadcast!(nodes[0], true);
5367 check_added_monitors!(nodes[0], 1);
5368 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5370 let htlc_timeout = {
5371 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5372 assert_eq!(node_txn.len(), 1);
5373 assert_eq!(node_txn[0].input.len(), 1);
5374 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5375 check_spends!(node_txn[0], local_txn_1[0]);
5379 mine_transaction(&nodes[0], &htlc_timeout);
5380 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5381 expect_payment_failed!(nodes[0], our_payment_hash, false);
5383 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5384 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5385 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5386 assert_eq!(spend_txn.len(), 3);
5387 check_spends!(spend_txn[0], local_txn_1[0]);
5388 assert_eq!(spend_txn[1].input.len(), 1);
5389 check_spends!(spend_txn[1], htlc_timeout);
5390 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5391 assert_eq!(spend_txn[2].input.len(), 2);
5392 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5393 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5394 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5398 fn test_static_output_closing_tx() {
5399 let chanmon_cfgs = create_chanmon_cfgs(2);
5400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5404 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5406 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5407 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5409 mine_transaction(&nodes[0], &closing_tx);
5410 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5411 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5413 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5414 assert_eq!(spend_txn.len(), 1);
5415 check_spends!(spend_txn[0], closing_tx);
5417 mine_transaction(&nodes[1], &closing_tx);
5418 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5419 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5421 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5422 assert_eq!(spend_txn.len(), 1);
5423 check_spends!(spend_txn[0], closing_tx);
5426 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5427 let chanmon_cfgs = create_chanmon_cfgs(2);
5428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5431 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5433 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5435 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5436 // present in B's local commitment transaction, but none of A's commitment transactions.
5437 nodes[1].node.claim_funds(payment_preimage);
5438 check_added_monitors!(nodes[1], 1);
5439 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5441 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5442 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5443 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5445 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5446 check_added_monitors!(nodes[0], 1);
5447 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5448 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5449 check_added_monitors!(nodes[1], 1);
5451 let starting_block = nodes[1].best_block_info();
5452 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5453 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5454 connect_block(&nodes[1], &block);
5455 block.header.prev_blockhash = block.block_hash();
5457 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5458 check_closed_broadcast!(nodes[1], true);
5459 check_added_monitors!(nodes[1], 1);
5460 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5463 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5464 let chanmon_cfgs = create_chanmon_cfgs(2);
5465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5467 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5468 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5470 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5471 nodes[0].node.send_payment_with_route(&route, payment_hash,
5472 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5473 check_added_monitors!(nodes[0], 1);
5475 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5477 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5478 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5479 // to "time out" the HTLC.
5481 let starting_block = nodes[1].best_block_info();
5482 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5484 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5485 connect_block(&nodes[0], &block);
5486 block.header.prev_blockhash = block.block_hash();
5488 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5489 check_closed_broadcast!(nodes[0], true);
5490 check_added_monitors!(nodes[0], 1);
5491 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5494 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5495 let chanmon_cfgs = create_chanmon_cfgs(3);
5496 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5497 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5498 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5499 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5501 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5502 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5503 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5504 // actually revoked.
5505 let htlc_value = if use_dust { 50000 } else { 3000000 };
5506 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5507 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5508 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5509 check_added_monitors!(nodes[1], 1);
5511 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5512 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5513 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5514 check_added_monitors!(nodes[0], 1);
5515 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5516 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5517 check_added_monitors!(nodes[1], 1);
5518 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5519 check_added_monitors!(nodes[1], 1);
5520 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5522 if check_revoke_no_close {
5523 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5524 check_added_monitors!(nodes[0], 1);
5527 let starting_block = nodes[1].best_block_info();
5528 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5529 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5530 connect_block(&nodes[0], &block);
5531 block.header.prev_blockhash = block.block_hash();
5533 if !check_revoke_no_close {
5534 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5535 check_closed_broadcast!(nodes[0], true);
5536 check_added_monitors!(nodes[0], 1);
5537 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5539 expect_payment_failed!(nodes[0], our_payment_hash, true);
5543 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5544 // There are only a few cases to test here:
5545 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5546 // broadcastable commitment transactions result in channel closure,
5547 // * its included in an unrevoked-but-previous remote commitment transaction,
5548 // * its included in the latest remote or local commitment transactions.
5549 // We test each of the three possible commitment transactions individually and use both dust and
5551 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5552 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5553 // tested for at least one of the cases in other tests.
5555 fn htlc_claim_single_commitment_only_a() {
5556 do_htlc_claim_local_commitment_only(true);
5557 do_htlc_claim_local_commitment_only(false);
5559 do_htlc_claim_current_remote_commitment_only(true);
5560 do_htlc_claim_current_remote_commitment_only(false);
5564 fn htlc_claim_single_commitment_only_b() {
5565 do_htlc_claim_previous_remote_commitment_only(true, false);
5566 do_htlc_claim_previous_remote_commitment_only(false, false);
5567 do_htlc_claim_previous_remote_commitment_only(true, true);
5568 do_htlc_claim_previous_remote_commitment_only(false, true);
5573 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5574 let chanmon_cfgs = create_chanmon_cfgs(2);
5575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5578 // Force duplicate randomness for every get-random call
5579 for node in nodes.iter() {
5580 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5583 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5584 let channel_value_satoshis=10000;
5585 let push_msat=10001;
5586 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5587 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5588 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5589 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5591 // Create a second channel with the same random values. This used to panic due to a colliding
5592 // channel_id, but now panics due to a colliding outbound SCID alias.
5593 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5597 fn bolt2_open_channel_sending_node_checks_part2() {
5598 let chanmon_cfgs = create_chanmon_cfgs(2);
5599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5601 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5603 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5604 let channel_value_satoshis=2^24;
5605 let push_msat=10001;
5606 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5608 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5609 let channel_value_satoshis=10000;
5610 // Test when push_msat is equal to 1000 * funding_satoshis.
5611 let push_msat=1000*channel_value_satoshis+1;
5612 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5614 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5615 let channel_value_satoshis=10000;
5616 let push_msat=10001;
5617 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
5618 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5619 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5621 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5622 // 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
5623 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5625 // 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.
5626 assert!(BREAKDOWN_TIMEOUT>0);
5627 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5629 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5630 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5631 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5633 // 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.
5634 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5635 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5636 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5637 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5638 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5642 fn bolt2_open_channel_sane_dust_limit() {
5643 let chanmon_cfgs = create_chanmon_cfgs(2);
5644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5646 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5648 let channel_value_satoshis=1000000;
5649 let push_msat=10001;
5650 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5651 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5652 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5653 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5655 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5656 let events = nodes[1].node.get_and_clear_pending_msg_events();
5657 let err_msg = match events[0] {
5658 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5661 _ => panic!("Unexpected event"),
5663 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5666 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5667 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5668 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5669 // is no longer affordable once it's freed.
5671 fn test_fail_holding_cell_htlc_upon_free() {
5672 let chanmon_cfgs = create_chanmon_cfgs(2);
5673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5676 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5678 // First nodes[0] generates an update_fee, setting the channel's
5679 // pending_update_fee.
5681 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5682 *feerate_lock += 20;
5684 nodes[0].node.timer_tick_occurred();
5685 check_added_monitors!(nodes[0], 1);
5687 let events = nodes[0].node.get_and_clear_pending_msg_events();
5688 assert_eq!(events.len(), 1);
5689 let (update_msg, commitment_signed) = match events[0] {
5690 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5691 (update_fee.as_ref(), commitment_signed)
5693 _ => panic!("Unexpected event"),
5696 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5698 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5699 let channel_reserve = chan_stat.channel_reserve_msat;
5700 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5701 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5703 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5704 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5705 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5707 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5708 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5709 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5710 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5711 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5713 // Flush the pending fee update.
5714 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5715 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5716 check_added_monitors!(nodes[1], 1);
5717 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5718 check_added_monitors!(nodes[0], 1);
5720 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5721 // HTLC, but now that the fee has been raised the payment will now fail, causing
5722 // us to surface its failure to the user.
5723 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5724 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5725 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);
5726 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 {}",
5727 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5728 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5730 // Check that the payment failed to be sent out.
5731 let events = nodes[0].node.get_and_clear_pending_events();
5732 assert_eq!(events.len(), 2);
5734 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5735 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5736 assert_eq!(our_payment_hash.clone(), *payment_hash);
5737 assert_eq!(*payment_failed_permanently, false);
5738 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5740 _ => panic!("Unexpected event"),
5743 &Event::PaymentFailed { ref payment_hash, .. } => {
5744 assert_eq!(our_payment_hash.clone(), *payment_hash);
5746 _ => panic!("Unexpected event"),
5750 // Test that if multiple HTLCs are released from the holding cell and one is
5751 // valid but the other is no longer valid upon release, the valid HTLC can be
5752 // successfully completed while the other one fails as expected.
5754 fn test_free_and_fail_holding_cell_htlcs() {
5755 let chanmon_cfgs = create_chanmon_cfgs(2);
5756 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5757 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5758 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5759 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5761 // First nodes[0] generates an update_fee, setting the channel's
5762 // pending_update_fee.
5764 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5765 *feerate_lock += 200;
5767 nodes[0].node.timer_tick_occurred();
5768 check_added_monitors!(nodes[0], 1);
5770 let events = nodes[0].node.get_and_clear_pending_msg_events();
5771 assert_eq!(events.len(), 1);
5772 let (update_msg, commitment_signed) = match events[0] {
5773 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5774 (update_fee.as_ref(), commitment_signed)
5776 _ => panic!("Unexpected event"),
5779 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5781 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5782 let channel_reserve = chan_stat.channel_reserve_msat;
5783 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5784 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5786 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5788 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5789 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5790 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5792 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5793 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5794 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5795 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5796 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5797 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5798 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5799 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5800 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5801 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5803 // Flush the pending fee update.
5804 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5805 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5806 check_added_monitors!(nodes[1], 1);
5807 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5808 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5809 check_added_monitors!(nodes[0], 2);
5811 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5812 // but now that the fee has been raised the second payment will now fail, causing us
5813 // to surface its failure to the user. The first payment should succeed.
5814 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5815 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5816 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);
5817 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 {}",
5818 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5819 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5821 // Check that the second payment failed to be sent out.
5822 let events = nodes[0].node.get_and_clear_pending_events();
5823 assert_eq!(events.len(), 2);
5825 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5826 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5827 assert_eq!(payment_hash_2.clone(), *payment_hash);
5828 assert_eq!(*payment_failed_permanently, false);
5829 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5831 _ => panic!("Unexpected event"),
5834 &Event::PaymentFailed { ref payment_hash, .. } => {
5835 assert_eq!(payment_hash_2.clone(), *payment_hash);
5837 _ => panic!("Unexpected event"),
5840 // Complete the first payment and the RAA from the fee update.
5841 let (payment_event, send_raa_event) = {
5842 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5843 assert_eq!(msgs.len(), 2);
5844 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5846 let raa = match send_raa_event {
5847 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5848 _ => panic!("Unexpected event"),
5850 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5851 check_added_monitors!(nodes[1], 1);
5852 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5853 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5854 let events = nodes[1].node.get_and_clear_pending_events();
5855 assert_eq!(events.len(), 1);
5857 Event::PendingHTLCsForwardable { .. } => {},
5858 _ => panic!("Unexpected event"),
5860 nodes[1].node.process_pending_htlc_forwards();
5861 let events = nodes[1].node.get_and_clear_pending_events();
5862 assert_eq!(events.len(), 1);
5864 Event::PaymentClaimable { .. } => {},
5865 _ => panic!("Unexpected event"),
5867 nodes[1].node.claim_funds(payment_preimage_1);
5868 check_added_monitors!(nodes[1], 1);
5869 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5871 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5872 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5873 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5874 expect_payment_sent!(nodes[0], payment_preimage_1);
5877 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5878 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5879 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5882 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5883 let chanmon_cfgs = create_chanmon_cfgs(3);
5884 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5885 // When this test was written, the default base fee floated based on the HTLC count.
5886 // It is now fixed, so we simply set the fee to the expected value here.
5887 let mut config = test_default_channel_config();
5888 config.channel_config.forwarding_fee_base_msat = 196;
5889 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5890 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5891 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5892 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5894 // First nodes[1] generates an update_fee, setting the channel's
5895 // pending_update_fee.
5897 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5898 *feerate_lock += 20;
5900 nodes[1].node.timer_tick_occurred();
5901 check_added_monitors!(nodes[1], 1);
5903 let events = nodes[1].node.get_and_clear_pending_msg_events();
5904 assert_eq!(events.len(), 1);
5905 let (update_msg, commitment_signed) = match events[0] {
5906 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5907 (update_fee.as_ref(), commitment_signed)
5909 _ => panic!("Unexpected event"),
5912 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5914 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5915 let channel_reserve = chan_stat.channel_reserve_msat;
5916 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5917 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5919 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5921 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5922 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5923 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5924 let payment_event = {
5925 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5926 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5927 check_added_monitors!(nodes[0], 1);
5929 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5930 assert_eq!(events.len(), 1);
5932 SendEvent::from_event(events.remove(0))
5934 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5935 check_added_monitors!(nodes[1], 0);
5936 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5937 expect_pending_htlcs_forwardable!(nodes[1]);
5939 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5940 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5942 // Flush the pending fee update.
5943 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5944 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5945 check_added_monitors!(nodes[2], 1);
5946 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5947 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5948 check_added_monitors!(nodes[1], 2);
5950 // A final RAA message is generated to finalize the fee update.
5951 let events = nodes[1].node.get_and_clear_pending_msg_events();
5952 assert_eq!(events.len(), 1);
5954 let raa_msg = match &events[0] {
5955 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5958 _ => panic!("Unexpected event"),
5961 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5962 check_added_monitors!(nodes[2], 1);
5963 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5965 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5966 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5967 assert_eq!(process_htlc_forwards_event.len(), 2);
5968 match &process_htlc_forwards_event[0] {
5969 &Event::PendingHTLCsForwardable { .. } => {},
5970 _ => panic!("Unexpected event"),
5973 // In response, we call ChannelManager's process_pending_htlc_forwards
5974 nodes[1].node.process_pending_htlc_forwards();
5975 check_added_monitors!(nodes[1], 1);
5977 // This causes the HTLC to be failed backwards.
5978 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5979 assert_eq!(fail_event.len(), 1);
5980 let (fail_msg, commitment_signed) = match &fail_event[0] {
5981 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5982 assert_eq!(updates.update_add_htlcs.len(), 0);
5983 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5984 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5985 assert_eq!(updates.update_fail_htlcs.len(), 1);
5986 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5988 _ => panic!("Unexpected event"),
5991 // Pass the failure messages back to nodes[0].
5992 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5993 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5995 // Complete the HTLC failure+removal process.
5996 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5997 check_added_monitors!(nodes[0], 1);
5998 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5999 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6000 check_added_monitors!(nodes[1], 2);
6001 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6002 assert_eq!(final_raa_event.len(), 1);
6003 let raa = match &final_raa_event[0] {
6004 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6005 _ => panic!("Unexpected event"),
6007 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6008 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6009 check_added_monitors!(nodes[0], 1);
6012 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6013 // 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.
6014 //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.
6017 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6018 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6019 let chanmon_cfgs = create_chanmon_cfgs(2);
6020 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6021 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6022 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6023 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6025 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6026 route.paths[0].hops[0].fee_msat = 100;
6028 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6029 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6030 ), true, APIError::ChannelUnavailable { ref err },
6031 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6032 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6033 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6037 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6038 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6039 let chanmon_cfgs = create_chanmon_cfgs(2);
6040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6042 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6043 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6045 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6046 route.paths[0].hops[0].fee_msat = 0;
6047 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6048 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6049 true, APIError::ChannelUnavailable { ref err },
6050 assert_eq!(err, "Cannot send 0-msat HTLC"));
6052 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6053 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6057 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6058 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6059 let chanmon_cfgs = create_chanmon_cfgs(2);
6060 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6061 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6062 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6063 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6065 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6066 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6067 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6068 check_added_monitors!(nodes[0], 1);
6069 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6070 updates.update_add_htlcs[0].amount_msat = 0;
6072 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6073 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6074 check_closed_broadcast!(nodes[1], true).unwrap();
6075 check_added_monitors!(nodes[1], 1);
6076 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6080 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6081 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6082 //It is enforced when constructing a route.
6083 let chanmon_cfgs = create_chanmon_cfgs(2);
6084 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6085 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6086 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6087 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6089 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6090 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6091 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6092 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6093 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6094 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6095 ), true, APIError::InvalidRoute { ref err },
6096 assert_eq!(err, &"Channel CLTV overflowed?"));
6100 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6101 //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.
6102 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6103 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6104 let chanmon_cfgs = create_chanmon_cfgs(2);
6105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6107 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6108 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6109 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6110 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6112 for i in 0..max_accepted_htlcs {
6113 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6114 let payment_event = {
6115 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6116 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6117 check_added_monitors!(nodes[0], 1);
6119 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6120 assert_eq!(events.len(), 1);
6121 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6122 assert_eq!(htlcs[0].htlc_id, i);
6126 SendEvent::from_event(events.remove(0))
6128 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6129 check_added_monitors!(nodes[1], 0);
6130 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6132 expect_pending_htlcs_forwardable!(nodes[1]);
6133 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6135 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6136 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6137 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6138 ), true, APIError::ChannelUnavailable { ref err },
6139 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6141 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6142 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6146 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6147 //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.
6148 let chanmon_cfgs = create_chanmon_cfgs(2);
6149 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6150 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6151 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6152 let channel_value = 100000;
6153 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6154 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6156 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6158 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6159 // Manually create a route over our max in flight (which our router normally automatically
6161 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6162 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6163 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6164 ), true, APIError::ChannelUnavailable { ref err },
6165 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)));
6167 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6168 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);
6170 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6173 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6175 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6176 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6177 let chanmon_cfgs = create_chanmon_cfgs(2);
6178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6180 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6181 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6182 let htlc_minimum_msat: u64;
6184 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6185 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6186 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6187 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6190 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6191 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6192 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6193 check_added_monitors!(nodes[0], 1);
6194 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6195 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6196 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6197 assert!(nodes[1].node.list_channels().is_empty());
6198 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6199 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()));
6200 check_added_monitors!(nodes[1], 1);
6201 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6205 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6206 //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
6207 let chanmon_cfgs = create_chanmon_cfgs(2);
6208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6210 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6211 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6213 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6214 let channel_reserve = chan_stat.channel_reserve_msat;
6215 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6216 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6217 // The 2* and +1 are for the fee spike reserve.
6218 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6220 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6221 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6222 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6223 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6224 check_added_monitors!(nodes[0], 1);
6225 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6227 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6228 // at this time channel-initiatee receivers are not required to enforce that senders
6229 // respect the fee_spike_reserve.
6230 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6231 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6233 assert!(nodes[1].node.list_channels().is_empty());
6234 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6235 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6236 check_added_monitors!(nodes[1], 1);
6237 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6241 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6242 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6243 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6244 let chanmon_cfgs = create_chanmon_cfgs(2);
6245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6247 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6248 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6250 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6251 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6252 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6253 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6254 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6255 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6256 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6258 let mut msg = msgs::UpdateAddHTLC {
6262 payment_hash: our_payment_hash,
6263 cltv_expiry: htlc_cltv,
6264 onion_routing_packet: onion_packet.clone(),
6268 msg.htlc_id = i as u64;
6269 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6271 msg.htlc_id = (50) as u64;
6272 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6274 assert!(nodes[1].node.list_channels().is_empty());
6275 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6276 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6277 check_added_monitors!(nodes[1], 1);
6278 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6282 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6283 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6284 let chanmon_cfgs = create_chanmon_cfgs(2);
6285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6287 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6290 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6291 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6292 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6293 check_added_monitors!(nodes[0], 1);
6294 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6295 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;
6296 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6298 assert!(nodes[1].node.list_channels().is_empty());
6299 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6300 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6301 check_added_monitors!(nodes[1], 1);
6302 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6306 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6307 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6308 let chanmon_cfgs = create_chanmon_cfgs(2);
6309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6311 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6313 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6314 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6315 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6316 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6317 check_added_monitors!(nodes[0], 1);
6318 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6319 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6320 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6322 assert!(nodes[1].node.list_channels().is_empty());
6323 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6324 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6325 check_added_monitors!(nodes[1], 1);
6326 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6330 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6331 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6332 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6333 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6334 let chanmon_cfgs = create_chanmon_cfgs(2);
6335 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6336 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6337 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6339 create_announced_chan_between_nodes(&nodes, 0, 1);
6340 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6341 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6342 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6343 check_added_monitors!(nodes[0], 1);
6344 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6345 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6347 //Disconnect and Reconnect
6348 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6349 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6350 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6351 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6353 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6354 assert_eq!(reestablish_1.len(), 1);
6355 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6356 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6358 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6359 assert_eq!(reestablish_2.len(), 1);
6360 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6361 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6362 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6363 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6366 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6367 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6368 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6369 check_added_monitors!(nodes[1], 1);
6370 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6372 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6374 assert!(nodes[1].node.list_channels().is_empty());
6375 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6376 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6377 check_added_monitors!(nodes[1], 1);
6378 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6382 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6383 //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.
6385 let chanmon_cfgs = create_chanmon_cfgs(2);
6386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6390 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6391 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6392 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6394 check_added_monitors!(nodes[0], 1);
6395 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6396 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6398 let update_msg = msgs::UpdateFulfillHTLC{
6401 payment_preimage: our_payment_preimage,
6404 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6406 assert!(nodes[0].node.list_channels().is_empty());
6407 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6408 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()));
6409 check_added_monitors!(nodes[0], 1);
6410 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6414 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6415 //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.
6417 let chanmon_cfgs = create_chanmon_cfgs(2);
6418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6420 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6421 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6423 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6424 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6425 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6426 check_added_monitors!(nodes[0], 1);
6427 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6428 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6430 let update_msg = msgs::UpdateFailHTLC{
6433 reason: msgs::OnionErrorPacket { data: Vec::new()},
6436 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6438 assert!(nodes[0].node.list_channels().is_empty());
6439 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6440 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()));
6441 check_added_monitors!(nodes[0], 1);
6442 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6446 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6447 //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.
6449 let chanmon_cfgs = create_chanmon_cfgs(2);
6450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6451 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6452 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6453 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6455 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6456 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6457 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6458 check_added_monitors!(nodes[0], 1);
6459 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6460 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6461 let update_msg = msgs::UpdateFailMalformedHTLC{
6464 sha256_of_onion: [1; 32],
6465 failure_code: 0x8000,
6468 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6470 assert!(nodes[0].node.list_channels().is_empty());
6471 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6472 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()));
6473 check_added_monitors!(nodes[0], 1);
6474 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6478 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6479 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6481 let chanmon_cfgs = create_chanmon_cfgs(2);
6482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6484 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6485 create_announced_chan_between_nodes(&nodes, 0, 1);
6487 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6489 nodes[1].node.claim_funds(our_payment_preimage);
6490 check_added_monitors!(nodes[1], 1);
6491 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6493 let events = nodes[1].node.get_and_clear_pending_msg_events();
6494 assert_eq!(events.len(), 1);
6495 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6497 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, .. } } => {
6498 assert!(update_add_htlcs.is_empty());
6499 assert_eq!(update_fulfill_htlcs.len(), 1);
6500 assert!(update_fail_htlcs.is_empty());
6501 assert!(update_fail_malformed_htlcs.is_empty());
6502 assert!(update_fee.is_none());
6503 update_fulfill_htlcs[0].clone()
6505 _ => panic!("Unexpected event"),
6509 update_fulfill_msg.htlc_id = 1;
6511 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6513 assert!(nodes[0].node.list_channels().is_empty());
6514 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6515 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6516 check_added_monitors!(nodes[0], 1);
6517 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6521 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6522 //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.
6524 let chanmon_cfgs = create_chanmon_cfgs(2);
6525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6528 create_announced_chan_between_nodes(&nodes, 0, 1);
6530 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6532 nodes[1].node.claim_funds(our_payment_preimage);
6533 check_added_monitors!(nodes[1], 1);
6534 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6536 let events = nodes[1].node.get_and_clear_pending_msg_events();
6537 assert_eq!(events.len(), 1);
6538 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6540 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, .. } } => {
6541 assert!(update_add_htlcs.is_empty());
6542 assert_eq!(update_fulfill_htlcs.len(), 1);
6543 assert!(update_fail_htlcs.is_empty());
6544 assert!(update_fail_malformed_htlcs.is_empty());
6545 assert!(update_fee.is_none());
6546 update_fulfill_htlcs[0].clone()
6548 _ => panic!("Unexpected event"),
6552 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6554 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6556 assert!(nodes[0].node.list_channels().is_empty());
6557 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6558 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6559 check_added_monitors!(nodes[0], 1);
6560 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6564 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6565 //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.
6567 let chanmon_cfgs = create_chanmon_cfgs(2);
6568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6570 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6571 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6573 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6574 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6575 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6576 check_added_monitors!(nodes[0], 1);
6578 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6579 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6582 check_added_monitors!(nodes[1], 0);
6583 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6585 let events = nodes[1].node.get_and_clear_pending_msg_events();
6587 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6589 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, .. } } => {
6590 assert!(update_add_htlcs.is_empty());
6591 assert!(update_fulfill_htlcs.is_empty());
6592 assert!(update_fail_htlcs.is_empty());
6593 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6594 assert!(update_fee.is_none());
6595 update_fail_malformed_htlcs[0].clone()
6597 _ => panic!("Unexpected event"),
6600 update_msg.failure_code &= !0x8000;
6601 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6603 assert!(nodes[0].node.list_channels().is_empty());
6604 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6605 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6606 check_added_monitors!(nodes[0], 1);
6607 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6611 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6612 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6613 // * 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.
6615 let chanmon_cfgs = create_chanmon_cfgs(3);
6616 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6617 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6618 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6619 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6620 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6622 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6625 let mut payment_event = {
6626 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6627 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6628 check_added_monitors!(nodes[0], 1);
6629 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6630 assert_eq!(events.len(), 1);
6631 SendEvent::from_event(events.remove(0))
6633 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6634 check_added_monitors!(nodes[1], 0);
6635 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6636 expect_pending_htlcs_forwardable!(nodes[1]);
6637 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6638 assert_eq!(events_2.len(), 1);
6639 check_added_monitors!(nodes[1], 1);
6640 payment_event = SendEvent::from_event(events_2.remove(0));
6641 assert_eq!(payment_event.msgs.len(), 1);
6644 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6645 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6646 check_added_monitors!(nodes[2], 0);
6647 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6649 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6650 assert_eq!(events_3.len(), 1);
6651 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6653 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 } } => {
6654 assert!(update_add_htlcs.is_empty());
6655 assert!(update_fulfill_htlcs.is_empty());
6656 assert!(update_fail_htlcs.is_empty());
6657 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6658 assert!(update_fee.is_none());
6659 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6661 _ => panic!("Unexpected event"),
6665 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6667 check_added_monitors!(nodes[1], 0);
6668 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6669 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 }]);
6670 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6671 assert_eq!(events_4.len(), 1);
6673 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6675 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, .. } } => {
6676 assert!(update_add_htlcs.is_empty());
6677 assert!(update_fulfill_htlcs.is_empty());
6678 assert_eq!(update_fail_htlcs.len(), 1);
6679 assert!(update_fail_malformed_htlcs.is_empty());
6680 assert!(update_fee.is_none());
6682 _ => panic!("Unexpected event"),
6685 check_added_monitors!(nodes[1], 1);
6689 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6690 let chanmon_cfgs = create_chanmon_cfgs(3);
6691 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6692 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6693 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6694 create_announced_chan_between_nodes(&nodes, 0, 1);
6695 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6697 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6700 let mut payment_event = {
6701 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6702 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6703 check_added_monitors!(nodes[0], 1);
6704 SendEvent::from_node(&nodes[0])
6707 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6708 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6709 expect_pending_htlcs_forwardable!(nodes[1]);
6710 check_added_monitors!(nodes[1], 1);
6711 payment_event = SendEvent::from_node(&nodes[1]);
6712 assert_eq!(payment_event.msgs.len(), 1);
6715 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6716 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6717 check_added_monitors!(nodes[2], 0);
6718 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6720 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6721 assert_eq!(events_3.len(), 1);
6723 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6724 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6725 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6726 update_msg.failure_code |= 0x2000;
6728 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6729 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6731 _ => panic!("Unexpected event"),
6734 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6735 vec![HTLCDestination::NextHopChannel {
6736 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6737 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6738 assert_eq!(events_4.len(), 1);
6739 check_added_monitors!(nodes[1], 1);
6742 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6743 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6744 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6746 _ => panic!("Unexpected event"),
6749 let events_5 = nodes[0].node.get_and_clear_pending_events();
6750 assert_eq!(events_5.len(), 2);
6752 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6753 // the node originating the error to its next hop.
6755 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6757 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6758 assert!(is_permanent);
6759 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6761 _ => panic!("Unexpected event"),
6764 Event::PaymentFailed { payment_hash, .. } => {
6765 assert_eq!(payment_hash, our_payment_hash);
6767 _ => panic!("Unexpected event"),
6770 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6773 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6774 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6775 // 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
6776 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6778 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6779 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6780 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6781 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6782 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6783 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6785 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6786 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6788 // We route 2 dust-HTLCs between A and B
6789 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6790 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6791 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6793 // Cache one local commitment tx as previous
6794 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6796 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6797 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6798 check_added_monitors!(nodes[1], 0);
6799 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6800 check_added_monitors!(nodes[1], 1);
6802 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6803 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6804 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6805 check_added_monitors!(nodes[0], 1);
6807 // Cache one local commitment tx as lastest
6808 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6810 let events = nodes[0].node.get_and_clear_pending_msg_events();
6812 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6813 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6815 _ => panic!("Unexpected event"),
6818 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6819 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6821 _ => panic!("Unexpected event"),
6824 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6825 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6826 if announce_latest {
6827 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6829 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6832 check_closed_broadcast!(nodes[0], true);
6833 check_added_monitors!(nodes[0], 1);
6834 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6836 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6837 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6838 let events = nodes[0].node.get_and_clear_pending_events();
6839 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6840 assert_eq!(events.len(), 4);
6841 let mut first_failed = false;
6842 for event in events {
6844 Event::PaymentPathFailed { payment_hash, .. } => {
6845 if payment_hash == payment_hash_1 {
6846 assert!(!first_failed);
6847 first_failed = true;
6849 assert_eq!(payment_hash, payment_hash_2);
6852 Event::PaymentFailed { .. } => {}
6853 _ => panic!("Unexpected event"),
6859 fn test_failure_delay_dust_htlc_local_commitment() {
6860 do_test_failure_delay_dust_htlc_local_commitment(true);
6861 do_test_failure_delay_dust_htlc_local_commitment(false);
6864 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6865 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6866 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6867 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6868 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6869 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6870 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6872 let chanmon_cfgs = create_chanmon_cfgs(3);
6873 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6874 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6875 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6876 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6878 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6879 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6881 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6882 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6884 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6885 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6887 // We revoked bs_commitment_tx
6889 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6890 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6893 let mut timeout_tx = Vec::new();
6895 // We fail dust-HTLC 1 by broadcast of local commitment tx
6896 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6897 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6898 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6899 expect_payment_failed!(nodes[0], dust_hash, false);
6901 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6902 check_closed_broadcast!(nodes[0], true);
6903 check_added_monitors!(nodes[0], 1);
6904 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6905 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6906 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6907 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6908 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6909 mine_transaction(&nodes[0], &timeout_tx[0]);
6910 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6911 expect_payment_failed!(nodes[0], non_dust_hash, false);
6913 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6914 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6915 check_closed_broadcast!(nodes[0], true);
6916 check_added_monitors!(nodes[0], 1);
6917 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6918 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6920 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6921 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6922 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6923 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6924 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6925 // dust HTLC should have been failed.
6926 expect_payment_failed!(nodes[0], dust_hash, false);
6929 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6931 assert_eq!(timeout_tx[0].lock_time.0, 11);
6933 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6934 mine_transaction(&nodes[0], &timeout_tx[0]);
6935 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6936 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6937 expect_payment_failed!(nodes[0], non_dust_hash, false);
6942 fn test_sweep_outbound_htlc_failure_update() {
6943 do_test_sweep_outbound_htlc_failure_update(false, true);
6944 do_test_sweep_outbound_htlc_failure_update(false, false);
6945 do_test_sweep_outbound_htlc_failure_update(true, false);
6949 fn test_user_configurable_csv_delay() {
6950 // We test our channel constructors yield errors when we pass them absurd csv delay
6952 let mut low_our_to_self_config = UserConfig::default();
6953 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6954 let mut high_their_to_self_config = UserConfig::default();
6955 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6956 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6957 let chanmon_cfgs = create_chanmon_cfgs(2);
6958 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6959 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6960 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6962 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6963 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6964 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6965 &low_our_to_self_config, 0, 42)
6968 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())); },
6969 _ => panic!("Unexpected event"),
6971 } else { assert!(false) }
6973 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6974 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6975 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6976 open_channel.to_self_delay = 200;
6977 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6978 &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,
6979 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6982 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())); },
6983 _ => panic!("Unexpected event"),
6985 } else { assert!(false); }
6987 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6988 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6989 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()));
6990 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6991 accept_channel.to_self_delay = 200;
6992 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6994 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6996 &ErrorAction::SendErrorMessage { ref msg } => {
6997 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()));
6998 reason_msg = msg.data.clone();
7002 } else { panic!(); }
7003 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7005 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7006 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7007 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7008 open_channel.to_self_delay = 200;
7009 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7010 &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,
7011 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7014 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())); },
7015 _ => panic!("Unexpected event"),
7017 } else { assert!(false); }
7021 fn test_check_htlc_underpaying() {
7022 // Send payment through A -> B but A is maliciously
7023 // sending a probe payment (i.e less than expected value0
7024 // to B, B should refuse payment.
7026 let chanmon_cfgs = create_chanmon_cfgs(2);
7027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7029 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7031 // Create some initial channels
7032 create_announced_chan_between_nodes(&nodes, 0, 1);
7034 let scorer = test_utils::TestScorer::new();
7035 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7036 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();
7037 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();
7038 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7039 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7040 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7041 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7042 check_added_monitors!(nodes[0], 1);
7044 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7045 assert_eq!(events.len(), 1);
7046 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7047 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7048 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7050 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7051 // and then will wait a second random delay before failing the HTLC back:
7052 expect_pending_htlcs_forwardable!(nodes[1]);
7053 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7055 // Node 3 is expecting payment of 100_000 but received 10_000,
7056 // it should fail htlc like we didn't know the preimage.
7057 nodes[1].node.process_pending_htlc_forwards();
7059 let events = nodes[1].node.get_and_clear_pending_msg_events();
7060 assert_eq!(events.len(), 1);
7061 let (update_fail_htlc, commitment_signed) = match events[0] {
7062 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 } } => {
7063 assert!(update_add_htlcs.is_empty());
7064 assert!(update_fulfill_htlcs.is_empty());
7065 assert_eq!(update_fail_htlcs.len(), 1);
7066 assert!(update_fail_malformed_htlcs.is_empty());
7067 assert!(update_fee.is_none());
7068 (update_fail_htlcs[0].clone(), commitment_signed)
7070 _ => panic!("Unexpected event"),
7072 check_added_monitors!(nodes[1], 1);
7074 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7075 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7077 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7078 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7079 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7080 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7084 fn test_announce_disable_channels() {
7085 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7086 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7088 let chanmon_cfgs = create_chanmon_cfgs(2);
7089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7091 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7093 create_announced_chan_between_nodes(&nodes, 0, 1);
7094 create_announced_chan_between_nodes(&nodes, 1, 0);
7095 create_announced_chan_between_nodes(&nodes, 0, 1);
7098 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7099 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7101 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7102 nodes[0].node.timer_tick_occurred();
7104 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7105 assert_eq!(msg_events.len(), 3);
7106 let mut chans_disabled = HashMap::new();
7107 for e in msg_events {
7109 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7110 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7111 // Check that each channel gets updated exactly once
7112 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7113 panic!("Generated ChannelUpdate for wrong chan!");
7116 _ => panic!("Unexpected event"),
7120 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7121 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7123 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7124 assert_eq!(reestablish_1.len(), 3);
7125 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7126 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7128 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7129 assert_eq!(reestablish_2.len(), 3);
7131 // Reestablish chan_1
7132 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7133 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7134 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7135 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7136 // Reestablish chan_2
7137 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7138 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7139 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7140 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7141 // Reestablish chan_3
7142 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7143 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7144 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7145 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7147 for _ in 0..ENABLE_GOSSIP_TICKS {
7148 nodes[0].node.timer_tick_occurred();
7150 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7151 nodes[0].node.timer_tick_occurred();
7152 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7153 assert_eq!(msg_events.len(), 3);
7154 for e in msg_events {
7156 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7157 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7158 match chans_disabled.remove(&msg.contents.short_channel_id) {
7159 // Each update should have a higher timestamp than the previous one, replacing
7161 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7162 None => panic!("Generated ChannelUpdate for wrong chan!"),
7165 _ => panic!("Unexpected event"),
7168 // Check that each channel gets updated exactly once
7169 assert!(chans_disabled.is_empty());
7173 fn test_bump_penalty_txn_on_revoked_commitment() {
7174 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7175 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7177 let chanmon_cfgs = create_chanmon_cfgs(2);
7178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7180 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7182 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7184 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7185 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7186 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7187 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7188 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7190 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7191 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7192 assert_eq!(revoked_txn[0].output.len(), 4);
7193 assert_eq!(revoked_txn[0].input.len(), 1);
7194 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7195 let revoked_txid = revoked_txn[0].txid();
7197 let mut penalty_sum = 0;
7198 for outp in revoked_txn[0].output.iter() {
7199 if outp.script_pubkey.is_v0_p2wsh() {
7200 penalty_sum += outp.value;
7204 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7205 let header_114 = connect_blocks(&nodes[1], 14);
7207 // Actually revoke tx by claiming a HTLC
7208 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7209 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7210 check_added_monitors!(nodes[1], 1);
7212 // One or more justice tx should have been broadcast, check it
7216 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7217 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7218 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7219 assert_eq!(node_txn[0].output.len(), 1);
7220 check_spends!(node_txn[0], revoked_txn[0]);
7221 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7222 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7223 penalty_1 = node_txn[0].txid();
7227 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7228 connect_blocks(&nodes[1], 15);
7229 let mut penalty_2 = penalty_1;
7230 let mut feerate_2 = 0;
7232 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7233 assert_eq!(node_txn.len(), 1);
7234 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7235 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7236 assert_eq!(node_txn[0].output.len(), 1);
7237 check_spends!(node_txn[0], revoked_txn[0]);
7238 penalty_2 = node_txn[0].txid();
7239 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7240 assert_ne!(penalty_2, penalty_1);
7241 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7242 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7243 // Verify 25% bump heuristic
7244 assert!(feerate_2 * 100 >= feerate_1 * 125);
7248 assert_ne!(feerate_2, 0);
7250 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7251 connect_blocks(&nodes[1], 1);
7253 let mut feerate_3 = 0;
7255 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7256 assert_eq!(node_txn.len(), 1);
7257 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7258 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7259 assert_eq!(node_txn[0].output.len(), 1);
7260 check_spends!(node_txn[0], revoked_txn[0]);
7261 penalty_3 = node_txn[0].txid();
7262 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7263 assert_ne!(penalty_3, penalty_2);
7264 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7265 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7266 // Verify 25% bump heuristic
7267 assert!(feerate_3 * 100 >= feerate_2 * 125);
7271 assert_ne!(feerate_3, 0);
7273 nodes[1].node.get_and_clear_pending_events();
7274 nodes[1].node.get_and_clear_pending_msg_events();
7278 fn test_bump_penalty_txn_on_revoked_htlcs() {
7279 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7280 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7282 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7283 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7286 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7288 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7289 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7290 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7291 let scorer = test_utils::TestScorer::new();
7292 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7293 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7294 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7295 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7296 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7297 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7298 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7299 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7301 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7302 assert_eq!(revoked_local_txn[0].input.len(), 1);
7303 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7305 // Revoke local commitment tx
7306 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7308 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7309 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7310 check_closed_broadcast!(nodes[1], true);
7311 check_added_monitors!(nodes[1], 1);
7312 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7313 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7315 let revoked_htlc_txn = {
7316 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7317 assert_eq!(txn.len(), 2);
7319 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7320 assert_eq!(txn[0].input.len(), 1);
7321 check_spends!(txn[0], revoked_local_txn[0]);
7323 assert_eq!(txn[1].input.len(), 1);
7324 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7325 assert_eq!(txn[1].output.len(), 1);
7326 check_spends!(txn[1], revoked_local_txn[0]);
7331 // Broadcast set of revoked txn on A
7332 let hash_128 = connect_blocks(&nodes[0], 40);
7333 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7334 connect_block(&nodes[0], &block_11);
7335 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7336 connect_block(&nodes[0], &block_129);
7337 let events = nodes[0].node.get_and_clear_pending_events();
7338 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7339 match events.last().unwrap() {
7340 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7341 _ => panic!("Unexpected event"),
7347 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7348 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7349 // Verify claim tx are spending revoked HTLC txn
7351 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7352 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7353 // which are included in the same block (they are broadcasted because we scan the
7354 // transactions linearly and generate claims as we go, they likely should be removed in the
7356 assert_eq!(node_txn[0].input.len(), 1);
7357 check_spends!(node_txn[0], revoked_local_txn[0]);
7358 assert_eq!(node_txn[1].input.len(), 1);
7359 check_spends!(node_txn[1], revoked_local_txn[0]);
7360 assert_eq!(node_txn[2].input.len(), 1);
7361 check_spends!(node_txn[2], revoked_local_txn[0]);
7363 // Each of the three justice transactions claim a separate (single) output of the three
7364 // available, which we check here:
7365 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7366 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7367 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7369 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7370 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7372 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7373 // output, checked above).
7374 assert_eq!(node_txn[3].input.len(), 2);
7375 assert_eq!(node_txn[3].output.len(), 1);
7376 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7378 first = node_txn[3].txid();
7379 // Store both feerates for later comparison
7380 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7381 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7382 penalty_txn = vec![node_txn[2].clone()];
7386 // Connect one more block to see if bumped penalty are issued for HTLC txn
7387 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7388 connect_block(&nodes[0], &block_130);
7389 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7390 connect_block(&nodes[0], &block_131);
7392 // Few more blocks to confirm penalty txn
7393 connect_blocks(&nodes[0], 4);
7394 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7395 let header_144 = connect_blocks(&nodes[0], 9);
7397 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7398 assert_eq!(node_txn.len(), 1);
7400 assert_eq!(node_txn[0].input.len(), 2);
7401 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7402 // Verify bumped tx is different and 25% bump heuristic
7403 assert_ne!(first, node_txn[0].txid());
7404 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7405 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7406 assert!(feerate_2 * 100 > feerate_1 * 125);
7407 let txn = vec![node_txn[0].clone()];
7411 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7412 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7413 connect_blocks(&nodes[0], 20);
7415 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7416 // We verify than no new transaction has been broadcast because previously
7417 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7418 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7419 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7420 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7421 // up bumped justice generation.
7422 assert_eq!(node_txn.len(), 0);
7425 check_closed_broadcast!(nodes[0], true);
7426 check_added_monitors!(nodes[0], 1);
7430 fn test_bump_penalty_txn_on_remote_commitment() {
7431 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7432 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7435 // Provide preimage for one
7436 // Check aggregation
7438 let chanmon_cfgs = create_chanmon_cfgs(2);
7439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7441 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7443 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7444 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7445 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7447 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7448 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7449 assert_eq!(remote_txn[0].output.len(), 4);
7450 assert_eq!(remote_txn[0].input.len(), 1);
7451 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7453 // Claim a HTLC without revocation (provide B monitor with preimage)
7454 nodes[1].node.claim_funds(payment_preimage);
7455 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7456 mine_transaction(&nodes[1], &remote_txn[0]);
7457 check_added_monitors!(nodes[1], 2);
7458 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7460 // One or more claim tx should have been broadcast, check it
7464 let feerate_timeout;
7465 let feerate_preimage;
7467 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7468 // 3 transactions including:
7469 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7470 assert_eq!(node_txn.len(), 3);
7471 assert_eq!(node_txn[0].input.len(), 1);
7472 assert_eq!(node_txn[1].input.len(), 1);
7473 assert_eq!(node_txn[2].input.len(), 1);
7474 check_spends!(node_txn[0], remote_txn[0]);
7475 check_spends!(node_txn[1], remote_txn[0]);
7476 check_spends!(node_txn[2], remote_txn[0]);
7478 preimage = node_txn[0].txid();
7479 let index = node_txn[0].input[0].previous_output.vout;
7480 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7481 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7483 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7484 (node_txn[2].clone(), node_txn[1].clone())
7486 (node_txn[1].clone(), node_txn[2].clone())
7489 preimage_bump = preimage_bump_tx;
7490 check_spends!(preimage_bump, remote_txn[0]);
7491 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7493 timeout = timeout_tx.txid();
7494 let index = timeout_tx.input[0].previous_output.vout;
7495 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7496 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7500 assert_ne!(feerate_timeout, 0);
7501 assert_ne!(feerate_preimage, 0);
7503 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7504 connect_blocks(&nodes[1], 1);
7506 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7507 assert_eq!(node_txn.len(), 1);
7508 assert_eq!(node_txn[0].input.len(), 1);
7509 assert_eq!(preimage_bump.input.len(), 1);
7510 check_spends!(node_txn[0], remote_txn[0]);
7511 check_spends!(preimage_bump, remote_txn[0]);
7513 let index = preimage_bump.input[0].previous_output.vout;
7514 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7515 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7516 assert!(new_feerate * 100 > feerate_timeout * 125);
7517 assert_ne!(timeout, preimage_bump.txid());
7519 let index = node_txn[0].input[0].previous_output.vout;
7520 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7521 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7522 assert!(new_feerate * 100 > feerate_preimage * 125);
7523 assert_ne!(preimage, node_txn[0].txid());
7528 nodes[1].node.get_and_clear_pending_events();
7529 nodes[1].node.get_and_clear_pending_msg_events();
7533 fn test_counterparty_raa_skip_no_crash() {
7534 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7535 // commitment transaction, we would have happily carried on and provided them the next
7536 // commitment transaction based on one RAA forward. This would probably eventually have led to
7537 // channel closure, but it would not have resulted in funds loss. Still, our
7538 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7539 // check simply that the channel is closed in response to such an RAA, but don't check whether
7540 // we decide to punish our counterparty for revoking their funds (as we don't currently
7542 let chanmon_cfgs = create_chanmon_cfgs(2);
7543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7545 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7546 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7548 let per_commitment_secret;
7549 let next_per_commitment_point;
7551 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7552 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7553 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7555 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7557 // Make signer believe we got a counterparty signature, so that it allows the revocation
7558 keys.get_enforcement_state().last_holder_commitment -= 1;
7559 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7561 // Must revoke without gaps
7562 keys.get_enforcement_state().last_holder_commitment -= 1;
7563 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7565 keys.get_enforcement_state().last_holder_commitment -= 1;
7566 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7567 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7571 &msgs::RevokeAndACK {
7573 per_commitment_secret,
7574 next_per_commitment_point,
7576 next_local_nonce: None,
7578 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7579 check_added_monitors!(nodes[1], 1);
7580 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7584 fn test_bump_txn_sanitize_tracking_maps() {
7585 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7586 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7588 let chanmon_cfgs = create_chanmon_cfgs(2);
7589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7593 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7594 // Lock HTLC in both directions
7595 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7596 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7598 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7599 assert_eq!(revoked_local_txn[0].input.len(), 1);
7600 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7602 // Revoke local commitment tx
7603 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7605 // Broadcast set of revoked txn on A
7606 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7607 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7608 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7610 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7611 check_closed_broadcast!(nodes[0], true);
7612 check_added_monitors!(nodes[0], 1);
7613 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7615 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7616 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7617 check_spends!(node_txn[0], revoked_local_txn[0]);
7618 check_spends!(node_txn[1], revoked_local_txn[0]);
7619 check_spends!(node_txn[2], revoked_local_txn[0]);
7620 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7624 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7625 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7627 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7628 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7629 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7634 fn test_pending_claimed_htlc_no_balance_underflow() {
7635 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7636 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7637 let chanmon_cfgs = create_chanmon_cfgs(2);
7638 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7639 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7640 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7641 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7643 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7644 nodes[1].node.claim_funds(payment_preimage);
7645 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7646 check_added_monitors!(nodes[1], 1);
7647 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7649 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7650 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7651 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7652 check_added_monitors!(nodes[0], 1);
7653 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7655 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7656 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7657 // can get our balance.
7659 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7660 // the public key of the only hop. This works around ChannelDetails not showing the
7661 // almost-claimed HTLC as available balance.
7662 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7663 route.payment_params = None; // This is all wrong, but unnecessary
7664 route.paths[0].hops[0].pubkey = nodes[0].node.get_our_node_id();
7665 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7666 nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7667 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7669 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7673 fn test_channel_conf_timeout() {
7674 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7675 // confirm within 2016 blocks, as recommended by BOLT 2.
7676 let chanmon_cfgs = create_chanmon_cfgs(2);
7677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7681 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7683 // The outbound node should wait forever for confirmation:
7684 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7685 // copied here instead of directly referencing the constant.
7686 connect_blocks(&nodes[0], 2016);
7687 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7689 // The inbound node should fail the channel after exactly 2016 blocks
7690 connect_blocks(&nodes[1], 2015);
7691 check_added_monitors!(nodes[1], 0);
7692 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7694 connect_blocks(&nodes[1], 1);
7695 check_added_monitors!(nodes[1], 1);
7696 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7697 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7698 assert_eq!(close_ev.len(), 1);
7700 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7701 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7702 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7704 _ => panic!("Unexpected event"),
7709 fn test_override_channel_config() {
7710 let chanmon_cfgs = create_chanmon_cfgs(2);
7711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7715 // Node0 initiates a channel to node1 using the override config.
7716 let mut override_config = UserConfig::default();
7717 override_config.channel_handshake_config.our_to_self_delay = 200;
7719 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7721 // Assert the channel created by node0 is using the override config.
7722 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7723 assert_eq!(res.channel_flags, 0);
7724 assert_eq!(res.to_self_delay, 200);
7728 fn test_override_0msat_htlc_minimum() {
7729 let mut zero_config = UserConfig::default();
7730 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7731 let chanmon_cfgs = create_chanmon_cfgs(2);
7732 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7733 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7734 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7736 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7737 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7738 assert_eq!(res.htlc_minimum_msat, 1);
7740 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7741 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7742 assert_eq!(res.htlc_minimum_msat, 1);
7746 fn test_channel_update_has_correct_htlc_maximum_msat() {
7747 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7748 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7749 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7750 // 90% of the `channel_value`.
7751 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7753 let mut config_30_percent = UserConfig::default();
7754 config_30_percent.channel_handshake_config.announced_channel = true;
7755 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7756 let mut config_50_percent = UserConfig::default();
7757 config_50_percent.channel_handshake_config.announced_channel = true;
7758 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7759 let mut config_95_percent = UserConfig::default();
7760 config_95_percent.channel_handshake_config.announced_channel = true;
7761 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7762 let mut config_100_percent = UserConfig::default();
7763 config_100_percent.channel_handshake_config.announced_channel = true;
7764 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7766 let chanmon_cfgs = create_chanmon_cfgs(4);
7767 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7768 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)]);
7769 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7771 let channel_value_satoshis = 100000;
7772 let channel_value_msat = channel_value_satoshis * 1000;
7773 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7774 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7775 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7777 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7778 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7780 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7781 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7782 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7783 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7784 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7785 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7787 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7788 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7790 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7791 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7792 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7794 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7798 fn test_manually_accept_inbound_channel_request() {
7799 let mut manually_accept_conf = UserConfig::default();
7800 manually_accept_conf.manually_accept_inbound_channels = true;
7801 let chanmon_cfgs = create_chanmon_cfgs(2);
7802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7806 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7807 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7809 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7811 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7812 // accepting the inbound channel request.
7813 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7815 let events = nodes[1].node.get_and_clear_pending_events();
7817 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7818 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7820 _ => panic!("Unexpected event"),
7823 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7824 assert_eq!(accept_msg_ev.len(), 1);
7826 match accept_msg_ev[0] {
7827 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7828 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7830 _ => panic!("Unexpected event"),
7833 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7835 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7836 assert_eq!(close_msg_ev.len(), 1);
7838 let events = nodes[1].node.get_and_clear_pending_events();
7840 Event::ChannelClosed { user_channel_id, .. } => {
7841 assert_eq!(user_channel_id, 23);
7843 _ => panic!("Unexpected event"),
7848 fn test_manually_reject_inbound_channel_request() {
7849 let mut manually_accept_conf = UserConfig::default();
7850 manually_accept_conf.manually_accept_inbound_channels = true;
7851 let chanmon_cfgs = create_chanmon_cfgs(2);
7852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7856 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7857 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7859 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7861 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7862 // rejecting the inbound channel request.
7863 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7865 let events = nodes[1].node.get_and_clear_pending_events();
7867 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7868 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7870 _ => panic!("Unexpected event"),
7873 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7874 assert_eq!(close_msg_ev.len(), 1);
7876 match close_msg_ev[0] {
7877 MessageSendEvent::HandleError { ref node_id, .. } => {
7878 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7880 _ => panic!("Unexpected event"),
7882 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7886 fn test_reject_funding_before_inbound_channel_accepted() {
7887 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7888 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7889 // the node operator before the counterparty sends a `FundingCreated` message. If a
7890 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7891 // and the channel should be closed.
7892 let mut manually_accept_conf = UserConfig::default();
7893 manually_accept_conf.manually_accept_inbound_channels = true;
7894 let chanmon_cfgs = create_chanmon_cfgs(2);
7895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7899 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7900 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7901 let temp_channel_id = res.temporary_channel_id;
7903 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7905 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7906 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7908 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7909 nodes[1].node.get_and_clear_pending_events();
7911 // Get the `AcceptChannel` message of `nodes[1]` without calling
7912 // `ChannelManager::accept_inbound_channel`, which generates a
7913 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7914 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7915 // succeed when `nodes[0]` is passed to it.
7916 let accept_chan_msg = {
7917 let mut node_1_per_peer_lock;
7918 let mut node_1_peer_state_lock;
7919 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7920 channel.get_accept_channel_message()
7922 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7924 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7926 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7927 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7929 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7930 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7932 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7933 assert_eq!(close_msg_ev.len(), 1);
7935 let expected_err = "FundingCreated message received before the channel was accepted";
7936 match close_msg_ev[0] {
7937 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7938 assert_eq!(msg.channel_id, temp_channel_id);
7939 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7940 assert_eq!(msg.data, expected_err);
7942 _ => panic!("Unexpected event"),
7945 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7949 fn test_can_not_accept_inbound_channel_twice() {
7950 let mut manually_accept_conf = UserConfig::default();
7951 manually_accept_conf.manually_accept_inbound_channels = true;
7952 let chanmon_cfgs = create_chanmon_cfgs(2);
7953 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7954 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7955 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7957 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7958 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7960 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7962 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7963 // accepting the inbound channel request.
7964 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7966 let events = nodes[1].node.get_and_clear_pending_events();
7968 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7969 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7970 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7972 Err(APIError::APIMisuseError { err }) => {
7973 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7975 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7976 Err(_) => panic!("Unexpected Error"),
7979 _ => panic!("Unexpected event"),
7982 // Ensure that the channel wasn't closed after attempting to accept it twice.
7983 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7984 assert_eq!(accept_msg_ev.len(), 1);
7986 match accept_msg_ev[0] {
7987 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7988 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7990 _ => panic!("Unexpected event"),
7995 fn test_can_not_accept_unknown_inbound_channel() {
7996 let chanmon_cfg = create_chanmon_cfgs(2);
7997 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7998 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7999 let nodes = create_network(2, &node_cfg, &node_chanmgr);
8001 let unknown_channel_id = [0; 32];
8002 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8004 Err(APIError::ChannelUnavailable { err }) => {
8005 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()));
8007 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8008 Err(_) => panic!("Unexpected Error"),
8013 fn test_onion_value_mpp_set_calculation() {
8014 // Test that we use the onion value `amt_to_forward` when
8015 // calculating whether we've reached the `total_msat` of an MPP
8016 // by having a routing node forward more than `amt_to_forward`
8017 // and checking that the receiving node doesn't generate
8018 // a PaymentClaimable event too early
8020 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8021 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8022 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8023 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8025 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8026 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8027 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8028 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8030 let total_msat = 100_000;
8031 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8032 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8033 let sample_path = route.paths.pop().unwrap();
8035 let mut path_1 = sample_path.clone();
8036 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8037 path_1.hops[0].short_channel_id = chan_1_id;
8038 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8039 path_1.hops[1].short_channel_id = chan_3_id;
8040 path_1.hops[1].fee_msat = 100_000;
8041 route.paths.push(path_1);
8043 let mut path_2 = sample_path.clone();
8044 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8045 path_2.hops[0].short_channel_id = chan_2_id;
8046 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8047 path_2.hops[1].short_channel_id = chan_4_id;
8048 path_2.hops[1].fee_msat = 1_000;
8049 route.paths.push(path_2);
8052 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8053 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8054 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8055 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8056 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8057 check_added_monitors!(nodes[0], expected_paths.len());
8059 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8060 assert_eq!(events.len(), expected_paths.len());
8063 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8064 let mut payment_event = SendEvent::from_event(ev);
8065 let mut prev_node = &nodes[0];
8067 for (idx, &node) in expected_paths[0].iter().enumerate() {
8068 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8070 if idx == 0 { // routing node
8071 let session_priv = [3; 32];
8072 let height = nodes[0].best_block_info().1;
8073 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8074 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8075 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8076 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8077 // Edit amt_to_forward to simulate the sender having set
8078 // the final amount and the routing node taking less fee
8079 onion_payloads[1].amt_to_forward = 99_000;
8080 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8081 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8084 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8085 check_added_monitors!(node, 0);
8086 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8087 expect_pending_htlcs_forwardable!(node);
8090 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8091 assert_eq!(events_2.len(), 1);
8092 check_added_monitors!(node, 1);
8093 payment_event = SendEvent::from_event(events_2.remove(0));
8094 assert_eq!(payment_event.msgs.len(), 1);
8096 let events_2 = node.node.get_and_clear_pending_events();
8097 assert!(events_2.is_empty());
8104 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8105 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8107 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8110 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8112 let routing_node_count = msat_amounts.len();
8113 let node_count = routing_node_count + 2;
8115 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8116 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8117 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8118 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8123 // Create channels for each amount
8124 let mut expected_paths = Vec::with_capacity(routing_node_count);
8125 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8126 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8127 for i in 0..routing_node_count {
8128 let routing_node = 2 + i;
8129 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8130 src_chan_ids.push(src_chan_id);
8131 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8132 dst_chan_ids.push(dst_chan_id);
8133 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8134 expected_paths.push(path);
8136 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8138 // Create a route for each amount
8139 let example_amount = 100000;
8140 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);
8141 let sample_path = route.paths.pop().unwrap();
8142 for i in 0..routing_node_count {
8143 let routing_node = 2 + i;
8144 let mut path = sample_path.clone();
8145 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8146 path.hops[0].short_channel_id = src_chan_ids[i];
8147 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8148 path.hops[1].short_channel_id = dst_chan_ids[i];
8149 path.hops[1].fee_msat = msat_amounts[i];
8150 route.paths.push(path);
8153 // Send payment with manually set total_msat
8154 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8155 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8156 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8157 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8158 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8159 check_added_monitors!(nodes[src_idx], expected_paths.len());
8161 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8162 assert_eq!(events.len(), expected_paths.len());
8163 let mut amount_received = 0;
8164 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8165 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8167 let current_path_amount = msat_amounts[path_idx];
8168 amount_received += current_path_amount;
8169 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8170 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8173 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8177 fn test_overshoot_mpp() {
8178 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8179 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8183 fn test_simple_mpp() {
8184 // Simple test of sending a multi-path payment.
8185 let chanmon_cfgs = create_chanmon_cfgs(4);
8186 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8187 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8188 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8190 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8191 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8192 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8193 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8195 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8196 let path = route.paths[0].clone();
8197 route.paths.push(path);
8198 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8199 route.paths[0].hops[0].short_channel_id = chan_1_id;
8200 route.paths[0].hops[1].short_channel_id = chan_3_id;
8201 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8202 route.paths[1].hops[0].short_channel_id = chan_2_id;
8203 route.paths[1].hops[1].short_channel_id = chan_4_id;
8204 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8205 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8209 fn test_preimage_storage() {
8210 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8211 let chanmon_cfgs = create_chanmon_cfgs(2);
8212 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8213 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8214 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8216 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8219 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8220 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8221 nodes[0].node.send_payment_with_route(&route, payment_hash,
8222 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8223 check_added_monitors!(nodes[0], 1);
8224 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8225 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8226 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8227 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8229 // Note that after leaving the above scope we have no knowledge of any arguments or return
8230 // values from previous calls.
8231 expect_pending_htlcs_forwardable!(nodes[1]);
8232 let events = nodes[1].node.get_and_clear_pending_events();
8233 assert_eq!(events.len(), 1);
8235 Event::PaymentClaimable { ref purpose, .. } => {
8237 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8238 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8240 _ => panic!("expected PaymentPurpose::InvoicePayment")
8243 _ => panic!("Unexpected event"),
8248 #[allow(deprecated)]
8249 fn test_secret_timeout() {
8250 // Simple test of payment secret storage time outs. After
8251 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8252 let chanmon_cfgs = create_chanmon_cfgs(2);
8253 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8254 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8255 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8257 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8259 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8261 // We should fail to register the same payment hash twice, at least until we've connected a
8262 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8263 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8264 assert_eq!(err, "Duplicate payment hash");
8265 } else { panic!(); }
8267 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8268 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8270 connect_block(&nodes[1], &block);
8271 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8272 assert_eq!(err, "Duplicate payment hash");
8273 } else { panic!(); }
8275 // If we then connect the second block, we should be able to register the same payment hash
8276 // again (this time getting a new payment secret).
8277 block.header.prev_blockhash = block.header.block_hash();
8278 block.header.time += 1;
8279 connect_block(&nodes[1], &block);
8280 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8281 assert_ne!(payment_secret_1, our_payment_secret);
8284 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8285 nodes[0].node.send_payment_with_route(&route, payment_hash,
8286 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8287 check_added_monitors!(nodes[0], 1);
8288 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8289 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8290 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8291 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8293 // Note that after leaving the above scope we have no knowledge of any arguments or return
8294 // values from previous calls.
8295 expect_pending_htlcs_forwardable!(nodes[1]);
8296 let events = nodes[1].node.get_and_clear_pending_events();
8297 assert_eq!(events.len(), 1);
8299 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8300 assert!(payment_preimage.is_none());
8301 assert_eq!(payment_secret, our_payment_secret);
8302 // We don't actually have the payment preimage with which to claim this payment!
8304 _ => panic!("Unexpected event"),
8309 fn test_bad_secret_hash() {
8310 // Simple test of unregistered payment hash/invalid payment secret handling
8311 let chanmon_cfgs = create_chanmon_cfgs(2);
8312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8314 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8316 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8318 let random_payment_hash = PaymentHash([42; 32]);
8319 let random_payment_secret = PaymentSecret([43; 32]);
8320 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8321 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8323 // All the below cases should end up being handled exactly identically, so we macro the
8324 // resulting events.
8325 macro_rules! handle_unknown_invalid_payment_data {
8326 ($payment_hash: expr) => {
8327 check_added_monitors!(nodes[0], 1);
8328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8329 let payment_event = SendEvent::from_event(events.pop().unwrap());
8330 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8331 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8333 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8334 // again to process the pending backwards-failure of the HTLC
8335 expect_pending_htlcs_forwardable!(nodes[1]);
8336 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8337 check_added_monitors!(nodes[1], 1);
8339 // We should fail the payment back
8340 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8341 match events.pop().unwrap() {
8342 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8343 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8344 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8346 _ => panic!("Unexpected event"),
8351 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8352 // Error data is the HTLC value (100,000) and current block height
8353 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8355 // Send a payment with the right payment hash but the wrong payment secret
8356 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8357 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8358 handle_unknown_invalid_payment_data!(our_payment_hash);
8359 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8361 // Send a payment with a random payment hash, but the right payment secret
8362 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8363 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8364 handle_unknown_invalid_payment_data!(random_payment_hash);
8365 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8367 // Send a payment with a random payment hash and random payment secret
8368 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8369 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8370 handle_unknown_invalid_payment_data!(random_payment_hash);
8371 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8375 fn test_update_err_monitor_lockdown() {
8376 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8377 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8378 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8381 // This scenario may happen in a watchtower setup, where watchtower process a block height
8382 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8383 // commitment at same time.
8385 let chanmon_cfgs = create_chanmon_cfgs(2);
8386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8390 // Create some initial channel
8391 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8392 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8394 // Rebalance the network to generate htlc in the two directions
8395 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8397 // Route a HTLC from node 0 to node 1 (but don't settle)
8398 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8400 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8401 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8402 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8403 let persister = test_utils::TestPersister::new();
8406 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8407 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8408 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8409 assert!(new_monitor == *monitor);
8412 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);
8413 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8416 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8417 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8418 // transaction lock time requirements here.
8419 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8420 watchtower.chain_monitor.block_connected(&block, 200);
8422 // Try to update ChannelMonitor
8423 nodes[1].node.claim_funds(preimage);
8424 check_added_monitors!(nodes[1], 1);
8425 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8427 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8428 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8429 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8431 let mut node_0_per_peer_lock;
8432 let mut node_0_peer_state_lock;
8433 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8434 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8435 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8436 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8437 } else { assert!(false); }
8439 // Our local monitor is in-sync and hasn't processed yet timeout
8440 check_added_monitors!(nodes[0], 1);
8441 let events = nodes[0].node.get_and_clear_pending_events();
8442 assert_eq!(events.len(), 1);
8446 fn test_concurrent_monitor_claim() {
8447 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8448 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8449 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8450 // state N+1 confirms. Alice claims output from state N+1.
8452 let chanmon_cfgs = create_chanmon_cfgs(2);
8453 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8454 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8455 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8457 // Create some initial channel
8458 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8459 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8461 // Rebalance the network to generate htlc in the two directions
8462 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8464 // Route a HTLC from node 0 to node 1 (but don't settle)
8465 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8467 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8468 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8469 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8470 let persister = test_utils::TestPersister::new();
8471 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8472 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8474 let watchtower_alice = {
8476 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8477 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8478 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8479 assert!(new_monitor == *monitor);
8482 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8483 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8486 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8487 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8488 // requirements here.
8489 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8490 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8491 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8493 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8495 let mut txn = alice_broadcaster.txn_broadcast();
8496 assert_eq!(txn.len(), 2);
8500 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8501 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8502 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8503 let persister = test_utils::TestPersister::new();
8504 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8505 let watchtower_bob = {
8507 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8508 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8509 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8510 assert!(new_monitor == *monitor);
8513 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8514 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8517 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8519 // Route another payment to generate another update with still previous HTLC pending
8520 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8521 nodes[1].node.send_payment_with_route(&route, payment_hash,
8522 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8523 check_added_monitors!(nodes[1], 1);
8525 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8526 assert_eq!(updates.update_add_htlcs.len(), 1);
8527 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8529 let mut node_0_per_peer_lock;
8530 let mut node_0_peer_state_lock;
8531 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8532 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8533 // Watchtower Alice should already have seen the block and reject the update
8534 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8535 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8536 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8537 } else { assert!(false); }
8539 // Our local monitor is in-sync and hasn't processed yet timeout
8540 check_added_monitors!(nodes[0], 1);
8542 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8543 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8545 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8548 let mut txn = bob_broadcaster.txn_broadcast();
8549 assert_eq!(txn.len(), 2);
8550 bob_state_y = txn.remove(0);
8553 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8554 let height = HTLC_TIMEOUT_BROADCAST + 1;
8555 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8556 check_closed_broadcast(&nodes[0], 1, true);
8557 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8558 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8559 check_added_monitors(&nodes[0], 1);
8561 let htlc_txn = alice_broadcaster.txn_broadcast();
8562 assert_eq!(htlc_txn.len(), 2);
8563 check_spends!(htlc_txn[0], bob_state_y);
8564 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8565 // it. However, she should, because it now has an invalid parent.
8566 check_spends!(htlc_txn[1], alice_state);
8571 fn test_pre_lockin_no_chan_closed_update() {
8572 // Test that if a peer closes a channel in response to a funding_created message we don't
8573 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8576 // Doing so would imply a channel monitor update before the initial channel monitor
8577 // registration, violating our API guarantees.
8579 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8580 // then opening a second channel with the same funding output as the first (which is not
8581 // rejected because the first channel does not exist in the ChannelManager) and closing it
8582 // before receiving funding_signed.
8583 let chanmon_cfgs = create_chanmon_cfgs(2);
8584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8588 // Create an initial channel
8589 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8590 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8591 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8592 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8593 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8595 // Move the first channel through the funding flow...
8596 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8598 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8599 check_added_monitors!(nodes[0], 0);
8601 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8602 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8603 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8604 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8605 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8609 fn test_htlc_no_detection() {
8610 // This test is a mutation to underscore the detection logic bug we had
8611 // before #653. HTLC value routed is above the remaining balance, thus
8612 // inverting HTLC and `to_remote` output. HTLC will come second and
8613 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8614 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8615 // outputs order detection for correct spending children filtring.
8617 let chanmon_cfgs = create_chanmon_cfgs(2);
8618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8620 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8622 // Create some initial channels
8623 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8625 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8626 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8627 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8628 assert_eq!(local_txn[0].input.len(), 1);
8629 assert_eq!(local_txn[0].output.len(), 3);
8630 check_spends!(local_txn[0], chan_1.3);
8632 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8633 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8634 connect_block(&nodes[0], &block);
8635 // We deliberately connect the local tx twice as this should provoke a failure calling
8636 // this test before #653 fix.
8637 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8638 check_closed_broadcast!(nodes[0], true);
8639 check_added_monitors!(nodes[0], 1);
8640 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8641 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8643 let htlc_timeout = {
8644 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8645 assert_eq!(node_txn.len(), 1);
8646 assert_eq!(node_txn[0].input.len(), 1);
8647 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8648 check_spends!(node_txn[0], local_txn[0]);
8652 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8653 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8654 expect_payment_failed!(nodes[0], our_payment_hash, false);
8657 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8658 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8659 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8660 // Carol, Alice would be the upstream node, and Carol the downstream.)
8662 // Steps of the test:
8663 // 1) Alice sends a HTLC to Carol through Bob.
8664 // 2) Carol doesn't settle the HTLC.
8665 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8666 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8667 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8668 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8669 // 5) Carol release the preimage to Bob off-chain.
8670 // 6) Bob claims the offered output on the broadcasted commitment.
8671 let chanmon_cfgs = create_chanmon_cfgs(3);
8672 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8673 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8674 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8676 // Create some initial channels
8677 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8678 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8680 // Steps (1) and (2):
8681 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8682 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8684 // Check that Alice's commitment transaction now contains an output for this HTLC.
8685 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8686 check_spends!(alice_txn[0], chan_ab.3);
8687 assert_eq!(alice_txn[0].output.len(), 2);
8688 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8689 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8690 assert_eq!(alice_txn.len(), 2);
8692 // Steps (3) and (4):
8693 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8694 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8695 let mut force_closing_node = 0; // Alice force-closes
8696 let mut counterparty_node = 1; // Bob if Alice force-closes
8699 if !broadcast_alice {
8700 force_closing_node = 1;
8701 counterparty_node = 0;
8703 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8704 check_closed_broadcast!(nodes[force_closing_node], true);
8705 check_added_monitors!(nodes[force_closing_node], 1);
8706 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8707 if go_onchain_before_fulfill {
8708 let txn_to_broadcast = match broadcast_alice {
8709 true => alice_txn.clone(),
8710 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8712 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8713 if broadcast_alice {
8714 check_closed_broadcast!(nodes[1], true);
8715 check_added_monitors!(nodes[1], 1);
8716 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8721 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8722 // process of removing the HTLC from their commitment transactions.
8723 nodes[2].node.claim_funds(payment_preimage);
8724 check_added_monitors!(nodes[2], 1);
8725 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8727 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8728 assert!(carol_updates.update_add_htlcs.is_empty());
8729 assert!(carol_updates.update_fail_htlcs.is_empty());
8730 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8731 assert!(carol_updates.update_fee.is_none());
8732 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8734 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8735 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8736 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8737 if !go_onchain_before_fulfill && broadcast_alice {
8738 let events = nodes[1].node.get_and_clear_pending_msg_events();
8739 assert_eq!(events.len(), 1);
8741 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8742 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8744 _ => panic!("Unexpected event"),
8747 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8748 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8749 // Carol<->Bob's updated commitment transaction info.
8750 check_added_monitors!(nodes[1], 2);
8752 let events = nodes[1].node.get_and_clear_pending_msg_events();
8753 assert_eq!(events.len(), 2);
8754 let bob_revocation = match events[0] {
8755 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8756 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8759 _ => panic!("Unexpected event"),
8761 let bob_updates = match events[1] {
8762 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8763 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8766 _ => panic!("Unexpected event"),
8769 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8770 check_added_monitors!(nodes[2], 1);
8771 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8772 check_added_monitors!(nodes[2], 1);
8774 let events = nodes[2].node.get_and_clear_pending_msg_events();
8775 assert_eq!(events.len(), 1);
8776 let carol_revocation = match events[0] {
8777 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8778 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8781 _ => panic!("Unexpected event"),
8783 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8784 check_added_monitors!(nodes[1], 1);
8786 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8787 // here's where we put said channel's commitment tx on-chain.
8788 let mut txn_to_broadcast = alice_txn.clone();
8789 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8790 if !go_onchain_before_fulfill {
8791 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8792 // If Bob was the one to force-close, he will have already passed these checks earlier.
8793 if broadcast_alice {
8794 check_closed_broadcast!(nodes[1], true);
8795 check_added_monitors!(nodes[1], 1);
8796 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8798 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8799 if broadcast_alice {
8800 assert_eq!(bob_txn.len(), 1);
8801 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8803 assert_eq!(bob_txn.len(), 2);
8804 check_spends!(bob_txn[0], chan_ab.3);
8809 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8810 // broadcasted commitment transaction.
8812 let script_weight = match broadcast_alice {
8813 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8814 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8816 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8817 // Bob force-closed and broadcasts the commitment transaction along with a
8818 // HTLC-output-claiming transaction.
8819 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8820 if broadcast_alice {
8821 assert_eq!(bob_txn.len(), 1);
8822 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8823 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8825 assert_eq!(bob_txn.len(), 2);
8826 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8827 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8833 fn test_onchain_htlc_settlement_after_close() {
8834 do_test_onchain_htlc_settlement_after_close(true, true);
8835 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8836 do_test_onchain_htlc_settlement_after_close(true, false);
8837 do_test_onchain_htlc_settlement_after_close(false, false);
8841 fn test_duplicate_temporary_channel_id_from_different_peers() {
8842 // Tests that we can accept two different `OpenChannel` requests with the same
8843 // `temporary_channel_id`, as long as they are from different peers.
8844 let chanmon_cfgs = create_chanmon_cfgs(3);
8845 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8846 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8847 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8849 // Create an first channel channel
8850 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8851 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8853 // Create an second channel
8854 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8855 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8857 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8858 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8859 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8861 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8862 // `temporary_channel_id` as they are from different peers.
8863 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8865 let events = nodes[0].node.get_and_clear_pending_msg_events();
8866 assert_eq!(events.len(), 1);
8868 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8869 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8870 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8872 _ => panic!("Unexpected event"),
8876 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8878 let events = nodes[0].node.get_and_clear_pending_msg_events();
8879 assert_eq!(events.len(), 1);
8881 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8882 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8883 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8885 _ => panic!("Unexpected event"),
8891 fn test_duplicate_chan_id() {
8892 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8893 // already open we reject it and keep the old channel.
8895 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8896 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8897 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8898 // updating logic for the existing channel.
8899 let chanmon_cfgs = create_chanmon_cfgs(2);
8900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8904 // Create an initial channel
8905 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8906 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8907 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8908 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()));
8910 // Try to create a second channel with the same temporary_channel_id as the first and check
8911 // that it is rejected.
8912 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8914 let events = nodes[1].node.get_and_clear_pending_msg_events();
8915 assert_eq!(events.len(), 1);
8917 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8918 // Technically, at this point, nodes[1] would be justified in thinking both the
8919 // first (valid) and second (invalid) channels are closed, given they both have
8920 // the same non-temporary channel_id. However, currently we do not, so we just
8921 // move forward with it.
8922 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8923 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8925 _ => panic!("Unexpected event"),
8929 // Move the first channel through the funding flow...
8930 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8932 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8933 check_added_monitors!(nodes[0], 0);
8935 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8936 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8938 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8939 assert_eq!(added_monitors.len(), 1);
8940 assert_eq!(added_monitors[0].0, funding_output);
8941 added_monitors.clear();
8943 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8945 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8947 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8948 let channel_id = funding_outpoint.to_channel_id();
8950 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8953 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8954 // Technically this is allowed by the spec, but we don't support it and there's little reason
8955 // to. Still, it shouldn't cause any other issues.
8956 open_chan_msg.temporary_channel_id = channel_id;
8957 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8959 let events = nodes[1].node.get_and_clear_pending_msg_events();
8960 assert_eq!(events.len(), 1);
8962 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8963 // Technically, at this point, nodes[1] would be justified in thinking both
8964 // channels are closed, but currently we do not, so we just move forward with it.
8965 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8966 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8968 _ => panic!("Unexpected event"),
8972 // Now try to create a second channel which has a duplicate funding output.
8973 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8974 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8975 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8976 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()));
8977 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8979 let funding_created = {
8980 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8981 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8982 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8983 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8984 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8985 // channelmanager in a possibly nonsense state instead).
8986 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8987 let logger = test_utils::TestLogger::new();
8988 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8990 check_added_monitors!(nodes[0], 0);
8991 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8992 // At this point we'll look up if the channel_id is present and immediately fail the channel
8993 // without trying to persist the `ChannelMonitor`.
8994 check_added_monitors!(nodes[1], 0);
8996 // ...still, nodes[1] will reject the duplicate channel.
8998 let events = nodes[1].node.get_and_clear_pending_msg_events();
8999 assert_eq!(events.len(), 1);
9001 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9002 // Technically, at this point, nodes[1] would be justified in thinking both
9003 // channels are closed, but currently we do not, so we just move forward with it.
9004 assert_eq!(msg.channel_id, channel_id);
9005 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9007 _ => panic!("Unexpected event"),
9011 // finally, finish creating the original channel and send a payment over it to make sure
9012 // everything is functional.
9013 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9015 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9016 assert_eq!(added_monitors.len(), 1);
9017 assert_eq!(added_monitors[0].0, funding_output);
9018 added_monitors.clear();
9020 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9022 let events_4 = nodes[0].node.get_and_clear_pending_events();
9023 assert_eq!(events_4.len(), 0);
9024 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9025 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9027 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9028 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9029 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9031 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9035 fn test_error_chans_closed() {
9036 // Test that we properly handle error messages, closing appropriate channels.
9038 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9039 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9040 // we can test various edge cases around it to ensure we don't regress.
9041 let chanmon_cfgs = create_chanmon_cfgs(3);
9042 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9043 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9044 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9046 // Create some initial channels
9047 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9048 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9049 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9051 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9052 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9053 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9055 // Closing a channel from a different peer has no effect
9056 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9057 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9059 // Closing one channel doesn't impact others
9060 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9061 check_added_monitors!(nodes[0], 1);
9062 check_closed_broadcast!(nodes[0], false);
9063 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9064 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9065 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9066 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);
9067 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);
9069 // A null channel ID should close all channels
9070 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9071 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9072 check_added_monitors!(nodes[0], 2);
9073 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9074 let events = nodes[0].node.get_and_clear_pending_msg_events();
9075 assert_eq!(events.len(), 2);
9077 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9078 assert_eq!(msg.contents.flags & 2, 2);
9080 _ => panic!("Unexpected event"),
9083 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9084 assert_eq!(msg.contents.flags & 2, 2);
9086 _ => panic!("Unexpected event"),
9088 // Note that at this point users of a standard PeerHandler will end up calling
9089 // peer_disconnected.
9090 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9091 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9093 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9094 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9095 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9099 fn test_invalid_funding_tx() {
9100 // Test that we properly handle invalid funding transactions sent to us from a peer.
9102 // Previously, all other major lightning implementations had failed to properly sanitize
9103 // funding transactions from their counterparties, leading to a multi-implementation critical
9104 // security vulnerability (though we always sanitized properly, we've previously had
9105 // un-released crashes in the sanitization process).
9107 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9108 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9109 // gave up on it. We test this here by generating such a transaction.
9110 let chanmon_cfgs = create_chanmon_cfgs(2);
9111 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9112 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9113 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9115 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9116 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()));
9117 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()));
9119 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9121 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9122 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9123 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9125 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9126 let wit_program_script: Script = wit_program.into();
9127 for output in tx.output.iter_mut() {
9128 // Make the confirmed funding transaction have a bogus script_pubkey
9129 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9132 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9133 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()));
9134 check_added_monitors!(nodes[1], 1);
9135 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9137 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()));
9138 check_added_monitors!(nodes[0], 1);
9139 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9141 let events_1 = nodes[0].node.get_and_clear_pending_events();
9142 assert_eq!(events_1.len(), 0);
9144 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9145 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9146 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9148 let expected_err = "funding tx had wrong script/value or output index";
9149 confirm_transaction_at(&nodes[1], &tx, 1);
9150 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9151 check_added_monitors!(nodes[1], 1);
9152 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9153 assert_eq!(events_2.len(), 1);
9154 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9155 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9156 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9157 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9158 } else { panic!(); }
9159 } else { panic!(); }
9160 assert_eq!(nodes[1].node.list_channels().len(), 0);
9162 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9163 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9164 // as its not 32 bytes long.
9165 let mut spend_tx = Transaction {
9166 version: 2i32, lock_time: PackedLockTime::ZERO,
9167 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9168 previous_output: BitcoinOutPoint {
9172 script_sig: Script::new(),
9173 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9174 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9176 output: vec![TxOut {
9178 script_pubkey: Script::new(),
9181 check_spends!(spend_tx, tx);
9182 mine_transaction(&nodes[1], &spend_tx);
9185 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9186 // In the first version of the chain::Confirm interface, after a refactor was made to not
9187 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9188 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9189 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9190 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9191 // spending transaction until height N+1 (or greater). This was due to the way
9192 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9193 // spending transaction at the height the input transaction was confirmed at, not whether we
9194 // should broadcast a spending transaction at the current height.
9195 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9196 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9197 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9198 // until we learned about an additional block.
9200 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9201 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9202 let chanmon_cfgs = create_chanmon_cfgs(3);
9203 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9204 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9205 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9206 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9208 create_announced_chan_between_nodes(&nodes, 0, 1);
9209 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9210 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9211 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9212 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9214 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9215 check_closed_broadcast!(nodes[1], true);
9216 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9217 check_added_monitors!(nodes[1], 1);
9218 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9219 assert_eq!(node_txn.len(), 1);
9221 let conf_height = nodes[1].best_block_info().1;
9222 if !test_height_before_timelock {
9223 connect_blocks(&nodes[1], 24 * 6);
9225 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9226 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9227 if test_height_before_timelock {
9228 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9229 // generate any events or broadcast any transactions
9230 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9231 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9233 // We should broadcast an HTLC transaction spending our funding transaction first
9234 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9235 assert_eq!(spending_txn.len(), 2);
9236 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9237 check_spends!(spending_txn[1], node_txn[0]);
9238 // We should also generate a SpendableOutputs event with the to_self output (as its
9240 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9241 assert_eq!(descriptor_spend_txn.len(), 1);
9243 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9244 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9245 // additional block built on top of the current chain.
9246 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9247 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9248 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 }]);
9249 check_added_monitors!(nodes[1], 1);
9251 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9252 assert!(updates.update_add_htlcs.is_empty());
9253 assert!(updates.update_fulfill_htlcs.is_empty());
9254 assert_eq!(updates.update_fail_htlcs.len(), 1);
9255 assert!(updates.update_fail_malformed_htlcs.is_empty());
9256 assert!(updates.update_fee.is_none());
9257 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9258 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9259 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9264 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9265 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9266 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9269 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9270 let chanmon_cfgs = create_chanmon_cfgs(2);
9271 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9272 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9273 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9275 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9277 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9278 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9279 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9281 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9284 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9285 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9286 check_added_monitors!(nodes[0], 1);
9287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9288 assert_eq!(events.len(), 1);
9289 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9290 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9291 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9293 expect_pending_htlcs_forwardable!(nodes[1]);
9294 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9297 // Note that we use a different PaymentId here to allow us to duplicativly pay
9298 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9299 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9300 check_added_monitors!(nodes[0], 1);
9301 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9302 assert_eq!(events.len(), 1);
9303 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9305 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9306 // At this point, nodes[1] would notice it has too much value for the payment. It will
9307 // assume the second is a privacy attack (no longer particularly relevant
9308 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9309 // the first HTLC delivered above.
9312 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9313 nodes[1].node.process_pending_htlc_forwards();
9315 if test_for_second_fail_panic {
9316 // Now we go fail back the first HTLC from the user end.
9317 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9319 let expected_destinations = vec![
9320 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9321 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9323 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9324 nodes[1].node.process_pending_htlc_forwards();
9326 check_added_monitors!(nodes[1], 1);
9327 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9328 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9330 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9331 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9332 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9334 let failure_events = nodes[0].node.get_and_clear_pending_events();
9335 assert_eq!(failure_events.len(), 4);
9336 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9337 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9338 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9339 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9341 // Let the second HTLC fail and claim the first
9342 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9343 nodes[1].node.process_pending_htlc_forwards();
9345 check_added_monitors!(nodes[1], 1);
9346 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9347 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9348 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9350 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9352 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9357 fn test_dup_htlc_second_fail_panic() {
9358 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9359 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9360 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9361 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9362 do_test_dup_htlc_second_rejected(true);
9366 fn test_dup_htlc_second_rejected() {
9367 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9368 // simply reject the second HTLC but are still able to claim the first HTLC.
9369 do_test_dup_htlc_second_rejected(false);
9373 fn test_inconsistent_mpp_params() {
9374 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9375 // such HTLC and allow the second to stay.
9376 let chanmon_cfgs = create_chanmon_cfgs(4);
9377 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9378 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9379 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9381 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9382 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9383 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9384 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9386 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9387 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9388 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9389 assert_eq!(route.paths.len(), 2);
9390 route.paths.sort_by(|path_a, _| {
9391 // Sort the path so that the path through nodes[1] comes first
9392 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9393 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9396 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9398 let cur_height = nodes[0].best_block_info().1;
9399 let payment_id = PaymentId([42; 32]);
9401 let session_privs = {
9402 // We create a fake route here so that we start with three pending HTLCs, which we'll
9403 // ultimately have, just not right away.
9404 let mut dup_route = route.clone();
9405 dup_route.paths.push(route.paths[1].clone());
9406 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9407 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9409 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9410 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9411 &None, session_privs[0]).unwrap();
9412 check_added_monitors!(nodes[0], 1);
9415 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9416 assert_eq!(events.len(), 1);
9417 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9419 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9421 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9422 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9423 check_added_monitors!(nodes[0], 1);
9426 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9427 assert_eq!(events.len(), 1);
9428 let payment_event = SendEvent::from_event(events.pop().unwrap());
9430 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9431 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9433 expect_pending_htlcs_forwardable!(nodes[2]);
9434 check_added_monitors!(nodes[2], 1);
9436 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9437 assert_eq!(events.len(), 1);
9438 let payment_event = SendEvent::from_event(events.pop().unwrap());
9440 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9441 check_added_monitors!(nodes[3], 0);
9442 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9444 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9445 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9446 // post-payment_secrets) and fail back the new HTLC.
9448 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9449 nodes[3].node.process_pending_htlc_forwards();
9450 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9451 nodes[3].node.process_pending_htlc_forwards();
9453 check_added_monitors!(nodes[3], 1);
9455 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9456 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9457 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9459 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 }]);
9460 check_added_monitors!(nodes[2], 1);
9462 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9463 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9464 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9466 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9468 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9469 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9470 &None, session_privs[2]).unwrap();
9471 check_added_monitors!(nodes[0], 1);
9473 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9474 assert_eq!(events.len(), 1);
9475 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9477 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9478 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9482 fn test_keysend_payments_to_public_node() {
9483 let chanmon_cfgs = create_chanmon_cfgs(2);
9484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9486 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9488 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9489 let network_graph = nodes[0].network_graph.clone();
9490 let payer_pubkey = nodes[0].node.get_our_node_id();
9491 let payee_pubkey = nodes[1].node.get_our_node_id();
9492 let route_params = RouteParameters {
9493 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9494 final_value_msat: 10000,
9496 let scorer = test_utils::TestScorer::new();
9497 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9498 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9500 let test_preimage = PaymentPreimage([42; 32]);
9501 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9502 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9503 check_added_monitors!(nodes[0], 1);
9504 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9505 assert_eq!(events.len(), 1);
9506 let event = events.pop().unwrap();
9507 let path = vec![&nodes[1]];
9508 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9509 claim_payment(&nodes[0], &path, test_preimage);
9513 fn test_keysend_payments_to_private_node() {
9514 let chanmon_cfgs = create_chanmon_cfgs(2);
9515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9519 let payer_pubkey = nodes[0].node.get_our_node_id();
9520 let payee_pubkey = nodes[1].node.get_our_node_id();
9522 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9523 let route_params = RouteParameters {
9524 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9525 final_value_msat: 10000,
9527 let network_graph = nodes[0].network_graph.clone();
9528 let first_hops = nodes[0].node.list_usable_channels();
9529 let scorer = test_utils::TestScorer::new();
9530 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9531 let route = find_route(
9532 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9533 nodes[0].logger, &scorer, &(), &random_seed_bytes
9536 let test_preimage = PaymentPreimage([42; 32]);
9537 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9538 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9539 check_added_monitors!(nodes[0], 1);
9540 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9541 assert_eq!(events.len(), 1);
9542 let event = events.pop().unwrap();
9543 let path = vec![&nodes[1]];
9544 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9545 claim_payment(&nodes[0], &path, test_preimage);
9549 fn test_double_partial_claim() {
9550 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9551 // time out, the sender resends only some of the MPP parts, then the user processes the
9552 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9554 let chanmon_cfgs = create_chanmon_cfgs(4);
9555 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9556 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9557 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9559 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9560 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9561 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9562 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9564 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9565 assert_eq!(route.paths.len(), 2);
9566 route.paths.sort_by(|path_a, _| {
9567 // Sort the path so that the path through nodes[1] comes first
9568 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9569 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9572 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9573 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9574 // amount of time to respond to.
9576 // Connect some blocks to time out the payment
9577 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9578 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9580 let failed_destinations = vec![
9581 HTLCDestination::FailedPayment { payment_hash },
9582 HTLCDestination::FailedPayment { payment_hash },
9584 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9586 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9588 // nodes[1] now retries one of the two paths...
9589 nodes[0].node.send_payment_with_route(&route, payment_hash,
9590 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9591 check_added_monitors!(nodes[0], 2);
9593 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9594 assert_eq!(events.len(), 2);
9595 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9596 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9598 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9599 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9600 nodes[3].node.claim_funds(payment_preimage);
9601 check_added_monitors!(nodes[3], 0);
9602 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9605 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9606 #[derive(Clone, Copy, PartialEq)]
9607 enum ExposureEvent {
9608 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9610 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9612 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9613 AtUpdateFeeOutbound,
9616 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9617 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9620 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9621 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9622 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9623 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9624 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9625 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9626 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9627 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9629 let chanmon_cfgs = create_chanmon_cfgs(2);
9630 let mut config = test_default_channel_config();
9631 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9634 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9636 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9637 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9638 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9639 open_channel.max_accepted_htlcs = 60;
9641 open_channel.dust_limit_satoshis = 546;
9643 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9644 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9645 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9647 let opt_anchors = false;
9649 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9652 let mut node_0_per_peer_lock;
9653 let mut node_0_peer_state_lock;
9654 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9655 chan.holder_dust_limit_satoshis = 546;
9658 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9659 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()));
9660 check_added_monitors!(nodes[1], 1);
9661 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9663 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()));
9664 check_added_monitors!(nodes[0], 1);
9665 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9667 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9668 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9669 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9671 let dust_buffer_feerate = {
9672 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9673 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9674 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9675 chan.get_dust_buffer_feerate(None) as u64
9677 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;
9678 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9680 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;
9681 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9683 let dust_htlc_on_counterparty_tx: u64 = 25;
9684 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9687 if dust_outbound_balance {
9688 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9689 // Outbound dust balance: 4372 sats
9690 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9691 for _ in 0..dust_outbound_htlc_on_holder_tx {
9692 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9693 nodes[0].node.send_payment_with_route(&route, payment_hash,
9694 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9697 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9698 // Inbound dust balance: 4372 sats
9699 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9700 for _ in 0..dust_inbound_htlc_on_holder_tx {
9701 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9705 if dust_outbound_balance {
9706 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9707 // Outbound dust balance: 5000 sats
9708 for _ in 0..dust_htlc_on_counterparty_tx {
9709 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9710 nodes[0].node.send_payment_with_route(&route, payment_hash,
9711 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9714 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9715 // Inbound dust balance: 5000 sats
9716 for _ in 0..dust_htlc_on_counterparty_tx {
9717 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9722 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9723 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9724 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 });
9725 let mut config = UserConfig::default();
9726 // With default dust exposure: 5000 sats
9728 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9729 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9730 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9731 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9732 ), true, APIError::ChannelUnavailable { ref err },
9733 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)));
9735 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9736 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9737 ), true, APIError::ChannelUnavailable { ref err },
9738 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)));
9740 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9741 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 });
9742 nodes[1].node.send_payment_with_route(&route, payment_hash,
9743 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9744 check_added_monitors!(nodes[1], 1);
9745 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9746 assert_eq!(events.len(), 1);
9747 let payment_event = SendEvent::from_event(events.remove(0));
9748 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9749 // With default dust exposure: 5000 sats
9751 // Outbound dust balance: 6399 sats
9752 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9753 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9754 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);
9756 // Outbound dust balance: 5200 sats
9757 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);
9759 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9760 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9761 nodes[0].node.send_payment_with_route(&route, payment_hash,
9762 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9764 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9765 *feerate_lock = *feerate_lock * 10;
9767 nodes[0].node.timer_tick_occurred();
9768 check_added_monitors!(nodes[0], 1);
9769 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9772 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9773 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9774 added_monitors.clear();
9778 fn test_max_dust_htlc_exposure() {
9779 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9780 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9781 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9782 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9783 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9784 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9785 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9786 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9787 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9788 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9789 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9790 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9794 fn test_non_final_funding_tx() {
9795 let chanmon_cfgs = create_chanmon_cfgs(2);
9796 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9797 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9798 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9800 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9801 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9802 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9803 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9804 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9806 let best_height = nodes[0].node.best_block.read().unwrap().height();
9808 let chan_id = *nodes[0].network_chan_count.borrow();
9809 let events = nodes[0].node.get_and_clear_pending_events();
9810 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9811 assert_eq!(events.len(), 1);
9812 let mut tx = match events[0] {
9813 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9814 // Timelock the transaction _beyond_ the best client height + 1.
9815 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9816 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9819 _ => panic!("Unexpected event"),
9821 // Transaction should fail as it's evaluated as non-final for propagation.
9822 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9823 Err(APIError::APIMisuseError { err }) => {
9824 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9829 // However, transaction should be accepted if it's in a +1 headroom from best block.
9830 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9831 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9832 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9836 fn accept_busted_but_better_fee() {
9837 // If a peer sends us a fee update that is too low, but higher than our previous channel
9838 // feerate, we should accept it. In the future we may want to consider closing the channel
9839 // later, but for now we only accept the update.
9840 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9841 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9842 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9843 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9845 create_chan_between_nodes(&nodes[0], &nodes[1]);
9847 // Set nodes[1] to expect 5,000 sat/kW.
9849 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9850 *feerate_lock = 5000;
9853 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9855 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9856 *feerate_lock = 1000;
9858 nodes[0].node.timer_tick_occurred();
9859 check_added_monitors!(nodes[0], 1);
9861 let events = nodes[0].node.get_and_clear_pending_msg_events();
9862 assert_eq!(events.len(), 1);
9864 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9865 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9866 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9868 _ => panic!("Unexpected event"),
9871 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9874 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9875 *feerate_lock = 2000;
9877 nodes[0].node.timer_tick_occurred();
9878 check_added_monitors!(nodes[0], 1);
9880 let events = nodes[0].node.get_and_clear_pending_msg_events();
9881 assert_eq!(events.len(), 1);
9883 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9884 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9885 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9887 _ => panic!("Unexpected event"),
9890 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9893 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9894 *feerate_lock = 1000;
9896 nodes[0].node.timer_tick_occurred();
9897 check_added_monitors!(nodes[0], 1);
9899 let events = nodes[0].node.get_and_clear_pending_msg_events();
9900 assert_eq!(events.len(), 1);
9902 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9903 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9904 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9905 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9906 check_closed_broadcast!(nodes[1], true);
9907 check_added_monitors!(nodes[1], 1);
9909 _ => panic!("Unexpected event"),
9913 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9914 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9917 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9918 let min_final_cltv_expiry_delta = 120;
9919 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9920 min_final_cltv_expiry_delta - 2 };
9921 let recv_value = 100_000;
9923 create_chan_between_nodes(&nodes[0], &nodes[1]);
9925 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9926 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9927 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9928 Some(recv_value), Some(min_final_cltv_expiry_delta));
9929 (payment_hash, payment_preimage, payment_secret)
9931 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9932 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9934 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9935 nodes[0].node.send_payment_with_route(&route, payment_hash,
9936 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9937 check_added_monitors!(nodes[0], 1);
9938 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9939 assert_eq!(events.len(), 1);
9940 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9942 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9943 expect_pending_htlcs_forwardable!(nodes[1]);
9946 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9947 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9949 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9951 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9953 check_added_monitors!(nodes[1], 1);
9955 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9956 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9957 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9959 expect_payment_failed!(nodes[0], payment_hash, true);
9964 fn test_payment_with_custom_min_cltv_expiry_delta() {
9965 do_payment_with_custom_min_final_cltv_expiry(false, false);
9966 do_payment_with_custom_min_final_cltv_expiry(false, true);
9967 do_payment_with_custom_min_final_cltv_expiry(true, false);
9968 do_payment_with_custom_min_final_cltv_expiry(true, true);
9972 fn test_disconnects_peer_awaiting_response_ticks() {
9973 // Tests that nodes which are awaiting on a response critical for channel responsiveness
9974 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9975 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9976 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9977 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9978 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9980 // Asserts a disconnect event is queued to the user.
9981 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9982 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9983 if let MessageSendEvent::HandleError { action, .. } = event {
9984 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9993 assert_eq!(disconnect_event.is_some(), should_disconnect);
9996 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9997 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9998 let check_disconnect = |node: &Node| {
9999 // No disconnect without any timer ticks.
10000 check_disconnect_event(node, false);
10002 // No disconnect with 1 timer tick less than required.
10003 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10004 node.node.timer_tick_occurred();
10005 check_disconnect_event(node, false);
10008 // Disconnect after reaching the required ticks.
10009 node.node.timer_tick_occurred();
10010 check_disconnect_event(node, true);
10012 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10013 node.node.timer_tick_occurred();
10014 check_disconnect_event(node, true);
10017 create_chan_between_nodes(&nodes[0], &nodes[1]);
10019 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10020 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10021 nodes[0].node.timer_tick_occurred();
10022 check_added_monitors!(&nodes[0], 1);
10023 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10024 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10025 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10026 check_added_monitors!(&nodes[1], 1);
10028 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10029 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10030 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10031 check_added_monitors!(&nodes[0], 1);
10032 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10033 check_added_monitors(&nodes[0], 1);
10035 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10036 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10037 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10038 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10039 check_disconnect(&nodes[1]);
10041 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10043 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10044 // final `RevokeAndACK` to Bob to complete it.
10045 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10046 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10047 let bob_init = msgs::Init {
10048 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10050 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10051 let alice_init = msgs::Init {
10052 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10054 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10056 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10057 // received Bob's yet, so she should disconnect him after reaching
10058 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10059 let alice_channel_reestablish = get_event_msg!(
10060 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10062 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10063 check_disconnect(&nodes[0]);
10065 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10066 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10067 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10068 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10074 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10076 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10077 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10078 nodes[0].node.timer_tick_occurred();
10079 check_disconnect_event(&nodes[0], false);
10082 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10083 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10084 check_disconnect(&nodes[1]);
10086 // Finally, have Bob process the last message.
10087 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10088 check_added_monitors(&nodes[1], 1);
10090 // At this point, neither node should attempt to disconnect each other, since they aren't
10091 // waiting on any messages.
10092 for node in &nodes {
10093 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10094 node.node.timer_tick_occurred();
10095 check_disconnect_event(node, false);