1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183 chan.holder_selected_channel_reserve_satoshis = 0;
184 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193 if send_from_initiator {
194 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195 // Note that for outbound channels we have to consider the commitment tx fee and the
196 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197 // well as an additional HTLC.
198 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200 send_payment(&nodes[1], &[&nodes[0]], push_amt);
205 fn test_counterparty_no_reserve() {
206 do_test_counterparty_no_reserve(true);
207 do_test_counterparty_no_reserve(false);
211 fn test_async_inbound_update_fee() {
212 let chanmon_cfgs = create_chanmon_cfgs(2);
213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216 create_announced_chan_between_nodes(&nodes, 0, 1);
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
223 // send (1) commitment_signed -.
224 // <- update_add_htlc/commitment_signed
225 // send (2) RAA (awaiting remote revoke) -.
226 // (1) commitment_signed is delivered ->
227 // .- send (3) RAA (awaiting remote revoke)
228 // (2) RAA is delivered ->
229 // .- send (4) commitment_signed
230 // <- (3) RAA is delivered
231 // send (5) commitment_signed -.
232 // <- (4) commitment_signed is delivered
234 // (5) commitment_signed is delivered ->
236 // (6) RAA is delivered ->
238 // First nodes[0] generates an update_fee
240 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
243 nodes[0].node.timer_tick_occurred();
244 check_added_monitors!(nodes[0], 1);
246 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247 assert_eq!(events_0.len(), 1);
248 let (update_msg, commitment_signed) = match events_0[0] { // (1)
249 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250 (update_fee.as_ref(), commitment_signed)
252 _ => panic!("Unexpected event"),
255 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261 check_added_monitors!(nodes[1], 1);
263 let payment_event = {
264 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265 assert_eq!(events_1.len(), 1);
266 SendEvent::from_event(events_1.remove(0))
268 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269 assert_eq!(payment_event.msgs.len(), 1);
271 // ...now when the messages get delivered everyone should be happy
272 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276 check_added_monitors!(nodes[0], 1);
278 // deliver(1), generate (3):
279 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[1], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290 assert!(bs_update.update_fee.is_none()); // (4)
291 check_added_monitors!(nodes[1], 1);
293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295 assert!(as_update.update_add_htlcs.is_empty()); // (5)
296 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299 assert!(as_update.update_fee.is_none()); // (5)
300 check_added_monitors!(nodes[0], 1);
302 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304 // only (6) so get_event_msg's assert(len == 1) passes
305 check_added_monitors!(nodes[0], 1);
307 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309 check_added_monitors!(nodes[1], 1);
311 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312 check_added_monitors!(nodes[0], 1);
314 let events_2 = nodes[0].node.get_and_clear_pending_events();
315 assert_eq!(events_2.len(), 1);
317 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318 _ => panic!("Unexpected event"),
321 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322 check_added_monitors!(nodes[1], 1);
326 fn test_update_fee_unordered_raa() {
327 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328 // crash in an earlier version of the update_fee patch)
329 let chanmon_cfgs = create_chanmon_cfgs(2);
330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333 create_announced_chan_between_nodes(&nodes, 0, 1);
336 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
338 // First nodes[0] generates an update_fee
340 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
343 nodes[0].node.timer_tick_occurred();
344 check_added_monitors!(nodes[0], 1);
346 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347 assert_eq!(events_0.len(), 1);
348 let update_msg = match events_0[0] { // (1)
349 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
352 _ => panic!("Unexpected event"),
355 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
357 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361 check_added_monitors!(nodes[1], 1);
363 let payment_event = {
364 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365 assert_eq!(events_1.len(), 1);
366 SendEvent::from_event(events_1.remove(0))
368 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369 assert_eq!(payment_event.msgs.len(), 1);
371 // ...now when the messages get delivered everyone should be happy
372 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376 check_added_monitors!(nodes[0], 1);
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379 check_added_monitors!(nodes[1], 1);
381 // We can't continue, sadly, because our (1) now has a bogus signature
385 fn test_multi_flight_update_fee() {
386 let chanmon_cfgs = create_chanmon_cfgs(2);
387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390 create_announced_chan_between_nodes(&nodes, 0, 1);
393 // update_fee/commitment_signed ->
394 // .- send (1) RAA and (2) commitment_signed
395 // update_fee (never committed) ->
397 // We have to manually generate the above update_fee, it is allowed by the protocol but we
398 // don't track which updates correspond to which revoke_and_ack responses so we're in
399 // AwaitingRAA mode and will not generate the update_fee yet.
400 // <- (1) RAA delivered
401 // (3) is generated and send (4) CS -.
402 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403 // know the per_commitment_point to use for it.
404 // <- (2) commitment_signed delivered
406 // B should send no response here
407 // (4) commitment_signed delivered ->
408 // <- RAA/commitment_signed delivered
411 // First nodes[0] generates an update_fee
414 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415 initial_feerate = *feerate_lock;
416 *feerate_lock = initial_feerate + 20;
418 nodes[0].node.timer_tick_occurred();
419 check_added_monitors!(nodes[0], 1);
421 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422 assert_eq!(events_0.len(), 1);
423 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425 (update_fee.as_ref().unwrap(), commitment_signed)
427 _ => panic!("Unexpected event"),
430 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434 check_added_monitors!(nodes[1], 1);
436 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
439 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440 *feerate_lock = initial_feerate + 40;
442 nodes[0].node.timer_tick_occurred();
443 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
446 // Create the (3) update_fee message that nodes[0] will generate before it does...
447 let mut update_msg_2 = msgs::UpdateFee {
448 channel_id: update_msg_1.channel_id.clone(),
449 feerate_per_kw: (initial_feerate + 30) as u32,
452 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
454 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
456 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
458 // Deliver (1), generating (3) and (4)
459 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 assert!(as_second_update.update_add_htlcs.is_empty());
463 assert!(as_second_update.update_fulfill_htlcs.is_empty());
464 assert!(as_second_update.update_fail_htlcs.is_empty());
465 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466 // Check that the update_fee newly generated matches what we delivered:
467 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
470 // Deliver (2) commitment_signed
471 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473 check_added_monitors!(nodes[0], 1);
474 // No commitment_signed so get_event_msg's assert(len == 1) passes
476 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[1], 1);
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[0], 1);
489 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491 // No commitment_signed so get_event_msg's assert(len == 1) passes
492 check_added_monitors!(nodes[0], 1);
494 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496 check_added_monitors!(nodes[1], 1);
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500 // Previously, we had issues deserializing channels when we hadn't connected the first block
501 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502 // serialization round-trips and simply do steps towards opening a channel and then drop the
505 let chanmon_cfgs = create_chanmon_cfgs(2);
506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
510 if steps & 0b1000_0000 != 0{
511 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512 connect_block(&nodes[0], &block);
513 connect_block(&nodes[1], &block);
516 if steps & 0x0f == 0 { return; }
517 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520 if steps & 0x0f == 1 { return; }
521 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524 if steps & 0x0f == 2 { return; }
525 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
527 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529 if steps & 0x0f == 3 { return; }
530 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531 check_added_monitors!(nodes[0], 0);
532 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534 if steps & 0x0f == 4 { return; }
535 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538 assert_eq!(added_monitors.len(), 1);
539 assert_eq!(added_monitors[0].0, funding_output);
540 added_monitors.clear();
542 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
544 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
546 if steps & 0x0f == 5 { return; }
547 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
549 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550 assert_eq!(added_monitors.len(), 1);
551 assert_eq!(added_monitors[0].0, funding_output);
552 added_monitors.clear();
555 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556 let events_4 = nodes[0].node.get_and_clear_pending_events();
557 assert_eq!(events_4.len(), 0);
559 if steps & 0x0f == 6 { return; }
560 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
562 if steps & 0x0f == 7 { return; }
563 confirm_transaction_at(&nodes[0], &tx, 2);
564 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
570 fn test_sanity_on_in_flight_opens() {
571 do_test_sanity_on_in_flight_opens(0);
572 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(1);
574 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(2);
576 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(3);
578 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(4);
580 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(5);
582 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(6);
584 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(7);
586 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(8);
588 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
592 fn test_update_fee_vanilla() {
593 let chanmon_cfgs = create_chanmon_cfgs(2);
594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597 create_announced_chan_between_nodes(&nodes, 0, 1);
600 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603 nodes[0].node.timer_tick_occurred();
604 check_added_monitors!(nodes[0], 1);
606 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607 assert_eq!(events_0.len(), 1);
608 let (update_msg, commitment_signed) = match events_0[0] {
609 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
610 (update_fee.as_ref(), commitment_signed)
612 _ => panic!("Unexpected event"),
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
616 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618 check_added_monitors!(nodes[1], 1);
620 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622 check_added_monitors!(nodes[0], 1);
624 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626 // No commitment_signed so get_event_msg's assert(len == 1) passes
627 check_added_monitors!(nodes[0], 1);
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631 check_added_monitors!(nodes[1], 1);
635 fn test_update_fee_that_funder_cannot_afford() {
636 let chanmon_cfgs = create_chanmon_cfgs(2);
637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640 let channel_value = 5000;
642 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643 let channel_id = chan.2;
644 let secp_ctx = Secp256k1::new();
645 let default_config = UserConfig::default();
646 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
648 let opt_anchors = false;
650 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652 // calculate two different feerates here - the expected local limit as well as the expected
654 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658 *feerate_lock = feerate;
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
662 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
666 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
668 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
670 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
672 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673 assert_eq!(commitment_tx.output.len(), 2);
674 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676 actual_fee = channel_value - actual_fee;
677 assert_eq!(total_fee, actual_fee);
681 // Increment the feerate by a small constant, accounting for rounding errors
682 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685 nodes[0].node.timer_tick_occurred();
686 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687 check_added_monitors!(nodes[0], 0);
689 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
691 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692 // needed to sign the new commitment tx and (2) sign the new commitment tx.
693 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697 let chan_signer = local_chan.get_signer();
698 let pubkeys = chan_signer.pubkeys();
699 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700 pubkeys.funding_pubkey)
702 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706 let chan_signer = remote_chan.get_signer();
707 let pubkeys = chan_signer.pubkeys();
708 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710 pubkeys.funding_pubkey)
713 // Assemble the set of keys we can use for signatures for our commitment_signed message.
714 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
718 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721 let local_chan_signer = local_chan.get_signer();
722 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724 INITIAL_COMMITMENT_NUMBER - 1,
726 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727 opt_anchors, local_funding, remote_funding,
728 commit_tx_keys.clone(),
729 non_buffer_feerate + 4,
731 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
733 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736 let commit_signed_msg = msgs::CommitmentSigned {
739 htlc_signatures: res.1,
741 partial_signature_with_nonce: None,
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
798 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799 assert_eq!(added_monitors.len(), 0);
800 added_monitors.clear();
802 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 // node[1] has nothing to do
806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 check_added_monitors!(nodes[0], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 check_added_monitors!(nodes[0], 1);
814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815 check_added_monitors!(nodes[1], 1);
816 // AwaitingRemoteRevoke ends here
818 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fee.is_none(), true);
825 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827 check_added_monitors!(nodes[0], 1);
828 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831 check_added_monitors!(nodes[1], 1);
832 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835 check_added_monitors!(nodes[1], 1);
836 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837 // No commitment_signed so get_event_msg's assert(len == 1) passes
839 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[0], 1);
841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
843 expect_pending_htlcs_forwardable!(nodes[0]);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentClaimable { .. } => { },
849 _ => panic!("Unexpected event"),
852 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
854 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
862 fn test_update_fee() {
863 let chanmon_cfgs = create_chanmon_cfgs(2);
864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868 let channel_id = chan.2;
871 // (1) update_fee/commitment_signed ->
872 // <- (2) revoke_and_ack
873 // .- send (3) commitment_signed
874 // (4) update_fee/commitment_signed ->
875 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876 // <- (3) commitment_signed delivered
877 // send (6) revoke_and_ack -.
878 // <- (5) deliver revoke_and_ack
879 // (6) deliver revoke_and_ack ->
880 // .- send (7) commitment_signed in response to (4)
881 // <- (7) deliver commitment_signed
884 // Create and deliver (1)...
887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888 feerate = *feerate_lock;
889 *feerate_lock = feerate + 20;
891 nodes[0].node.timer_tick_occurred();
892 check_added_monitors!(nodes[0], 1);
894 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895 assert_eq!(events_0.len(), 1);
896 let (update_msg, commitment_signed) = match events_0[0] {
897 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
898 (update_fee.as_ref(), commitment_signed)
900 _ => panic!("Unexpected event"),
902 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
904 // Generate (2) and (3):
905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912 check_added_monitors!(nodes[0], 1);
914 // Create and deliver (4)...
916 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917 *feerate_lock = feerate + 30;
919 nodes[0].node.timer_tick_occurred();
920 check_added_monitors!(nodes[0], 1);
921 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922 assert_eq!(events_0.len(), 1);
923 let (update_msg, commitment_signed) = match events_0[0] {
924 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
925 (update_fee.as_ref(), commitment_signed)
927 _ => panic!("Unexpected event"),
930 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932 check_added_monitors!(nodes[1], 1);
934 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
937 // Handle (3), creating (6):
938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939 check_added_monitors!(nodes[0], 1);
940 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 check_added_monitors!(nodes[0], 1);
948 // Deliver (6), creating (7):
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951 assert!(commitment_update.update_add_htlcs.is_empty());
952 assert!(commitment_update.update_fulfill_htlcs.is_empty());
953 assert!(commitment_update.update_fail_htlcs.is_empty());
954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955 assert!(commitment_update.update_fee.is_none());
956 check_added_monitors!(nodes[1], 1);
959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960 check_added_monitors!(nodes[0], 1);
961 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962 // No commitment_signed so get_event_msg's assert(len == 1) passes
964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965 check_added_monitors!(nodes[1], 1);
966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
968 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
976 fn fake_network_test() {
977 // Simple test which builds a network of ChannelManagers, connects them to each other, and
978 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979 let chanmon_cfgs = create_chanmon_cfgs(4);
980 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
984 // Create some initial channels
985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
989 // Rebalance the network a bit by relaying one payment through all the channels...
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 // Send some more payments
996 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1000 // Test failure packets
1001 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1004 // Add a new channel that skips 3
1005 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 // Do some rebalance loop payments, simultaneously
1016 let mut hops = Vec::with_capacity(3);
1017 hops.push(RouteHop {
1018 pubkey: nodes[2].node.get_our_node_id(),
1019 node_features: NodeFeatures::empty(),
1020 short_channel_id: chan_2.0.contents.short_channel_id,
1021 channel_features: ChannelFeatures::empty(),
1023 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1025 hops.push(RouteHop {
1026 pubkey: nodes[3].node.get_our_node_id(),
1027 node_features: NodeFeatures::empty(),
1028 short_channel_id: chan_3.0.contents.short_channel_id,
1029 channel_features: ChannelFeatures::empty(),
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 node_features: nodes[1].node.node_features(),
1036 short_channel_id: chan_4.0.contents.short_channel_id,
1037 channel_features: nodes[1].node.channel_features(),
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1042 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1043 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 node_features: NodeFeatures::empty(),
1049 short_channel_id: chan_4.0.contents.short_channel_id,
1050 channel_features: ChannelFeatures::empty(),
1052 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1054 hops.push(RouteHop {
1055 pubkey: nodes[2].node.get_our_node_id(),
1056 node_features: NodeFeatures::empty(),
1057 short_channel_id: chan_3.0.contents.short_channel_id,
1058 channel_features: ChannelFeatures::empty(),
1060 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1062 hops.push(RouteHop {
1063 pubkey: nodes[1].node.get_our_node_id(),
1064 node_features: nodes[1].node.node_features(),
1065 short_channel_id: chan_2.0.contents.short_channel_id,
1066 channel_features: nodes[1].node.channel_features(),
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1071 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1072 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 fn holding_cell_htlc_counting() {
1095 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097 // commitment dance rounds.
1098 let chanmon_cfgs = create_chanmon_cfgs(3);
1099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1105 let mut payments = Vec::new();
1107 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 nodes[1].node.send_payment_with_route(&route, payment_hash,
1109 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1110 payments.push((payment_preimage, payment_hash));
1112 check_added_monitors!(nodes[1], 1);
1114 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115 assert_eq!(events.len(), 1);
1116 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1119 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1122 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1124 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1125 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1126 ), true, APIError::ChannelUnavailable { ref err },
1127 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141 assert_eq!(events.len(), 1);
1142 let payment_event = SendEvent::from_event(events.pop().unwrap());
1143 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148 // fails), the second will process the resulting failure and fail the HTLC backward.
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1151 check_added_monitors!(nodes[1], 1);
1153 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1157 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1159 // Now forward all the pending HTLCs and claim them back
1160 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 for ref update in as_updates.update_add_htlcs.iter() {
1174 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1176 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177 check_added_monitors!(nodes[2], 1);
1178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179 check_added_monitors!(nodes[2], 1);
1180 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183 check_added_monitors!(nodes[1], 1);
1184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185 check_added_monitors!(nodes[1], 1);
1186 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1188 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189 check_added_monitors!(nodes[2], 1);
1191 expect_pending_htlcs_forwardable!(nodes[2]);
1193 let events = nodes[2].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), payments.len());
1195 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1197 &Event::PaymentClaimable { ref payment_hash, .. } => {
1198 assert_eq!(*payment_hash, *hash);
1200 _ => panic!("Unexpected event"),
1204 for (preimage, _) in payments.drain(..) {
1205 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 fn duplicate_htlc_test() {
1213 // Test that we accept duplicate payment_hash HTLCs across the network and that
1214 // claiming/failing them are all separate and don't affect each other
1215 let chanmon_cfgs = create_chanmon_cfgs(6);
1216 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1220 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221 create_announced_chan_between_nodes(&nodes, 0, 3);
1222 create_announced_chan_between_nodes(&nodes, 1, 3);
1223 create_announced_chan_between_nodes(&nodes, 2, 3);
1224 create_announced_chan_between_nodes(&nodes, 3, 4);
1225 create_announced_chan_between_nodes(&nodes, 3, 5);
1227 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1232 *nodes[0].network_payment_count.borrow_mut() -= 1;
1233 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1235 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242 // Test that ChannelMonitor doesn't generate 2 preimage txn
1243 // when we have 2 HTLCs with same preimage that go across a node
1244 // in opposite directions, even with the same payment secret.
1245 let chanmon_cfgs = create_chanmon_cfgs(2);
1246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1255 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1257 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1261 // Provide preimage to node 0 by claiming payment
1262 nodes[0].node.claim_funds(payment_preimage);
1263 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264 check_added_monitors!(nodes[0], 1);
1266 // Broadcast node 1 commitment txn
1267 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1269 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270 let mut has_both_htlcs = 0; // check htlcs match ones committed
1271 for outp in remote_txn[0].output.iter() {
1272 if outp.value == 800_000 / 1000 {
1273 has_both_htlcs += 1;
1274 } else if outp.value == 900_000 / 1000 {
1275 has_both_htlcs += 1;
1278 assert_eq!(has_both_htlcs, 2);
1280 mine_transaction(&nodes[0], &remote_txn[0]);
1281 check_added_monitors!(nodes[0], 1);
1282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 3);
1288 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289 check_spends!(claim_txn[1], remote_txn[0]);
1290 check_spends!(claim_txn[2], remote_txn[0]);
1291 let preimage_tx = &claim_txn[0];
1292 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293 (&claim_txn[1], &claim_txn[2])
1295 (&claim_txn[2], &claim_txn[1])
1298 assert_eq!(preimage_tx.input.len(), 1);
1299 assert_eq!(preimage_bump_tx.input.len(), 1);
1301 assert_eq!(preimage_tx.input.len(), 1);
1302 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1305 assert_eq!(timeout_tx.input.len(), 1);
1306 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307 check_spends!(timeout_tx, remote_txn[0]);
1308 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1310 let events = nodes[0].node.get_and_clear_pending_msg_events();
1311 assert_eq!(events.len(), 3);
1314 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1319 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1320 assert!(update_add_htlcs.is_empty());
1321 assert!(update_fail_htlcs.is_empty());
1322 assert_eq!(update_fulfill_htlcs.len(), 1);
1323 assert!(update_fail_malformed_htlcs.is_empty());
1324 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1326 _ => panic!("Unexpected event"),
1332 fn test_basic_channel_reserve() {
1333 let chanmon_cfgs = create_chanmon_cfgs(2);
1334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1339 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340 let channel_reserve = chan_stat.channel_reserve_msat;
1342 // The 2* and +1 are for the fee spike reserve.
1343 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1344 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345 let (mut route, our_payment_hash, _, our_payment_secret) =
1346 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1347 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1348 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1349 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1351 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1353 &APIError::ChannelUnavailable{ref err} =>
1354 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1355 _ => panic!("Unexpected error variant"),
1358 _ => panic!("Unexpected error variant"),
1360 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1361 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1363 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1367 fn test_fee_spike_violation_fails_htlc() {
1368 let chanmon_cfgs = create_chanmon_cfgs(2);
1369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1371 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1372 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1374 let (mut route, payment_hash, _, payment_secret) =
1375 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1376 route.paths[0].hops[0].fee_msat += 1;
1377 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1378 let secp_ctx = Secp256k1::new();
1379 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1381 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1383 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1384 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1385 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1386 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1387 let msg = msgs::UpdateAddHTLC {
1390 amount_msat: htlc_msat,
1391 payment_hash: payment_hash,
1392 cltv_expiry: htlc_cltv,
1393 onion_routing_packet: onion_packet,
1396 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1398 // Now manually create the commitment_signed message corresponding to the update_add
1399 // nodes[0] just sent. In the code for construction of this message, "local" refers
1400 // to the sender of the message, and "remote" refers to the receiver.
1402 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1404 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1406 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1407 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1408 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1409 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1410 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1411 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412 let chan_signer = local_chan.get_signer();
1413 // Make the signer believe we validated another commitment, so we can release the secret
1414 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1416 let pubkeys = chan_signer.pubkeys();
1417 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1418 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1419 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1420 chan_signer.pubkeys().funding_pubkey)
1422 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1423 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1424 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1425 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1426 let chan_signer = remote_chan.get_signer();
1427 let pubkeys = chan_signer.pubkeys();
1428 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1429 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1430 chan_signer.pubkeys().funding_pubkey)
1433 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1434 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1435 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1437 // Build the remote commitment transaction so we can sign it, and then later use the
1438 // signature for the commitment_signed message.
1439 let local_chan_balance = 1313;
1441 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1443 amount_msat: 3460001,
1444 cltv_expiry: htlc_cltv,
1446 transaction_output_index: Some(1),
1449 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1452 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1453 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1454 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1455 let local_chan_signer = local_chan.get_signer();
1456 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1460 local_chan.opt_anchors(), local_funding, remote_funding,
1461 commit_tx_keys.clone(),
1463 &mut vec![(accepted_htlc_info, ())],
1464 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1466 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1469 let commit_signed_msg = msgs::CommitmentSigned {
1472 htlc_signatures: res.1,
1474 partial_signature_with_nonce: None,
1477 // Send the commitment_signed message to the nodes[1].
1478 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1479 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1481 // Send the RAA to nodes[1].
1482 let raa_msg = msgs::RevokeAndACK {
1484 per_commitment_secret: local_secret,
1485 next_per_commitment_point: next_local_point,
1487 next_local_nonce: None,
1489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1491 let events = nodes[1].node.get_and_clear_pending_msg_events();
1492 assert_eq!(events.len(), 1);
1493 // Make sure the HTLC failed in the way we expect.
1495 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1496 assert_eq!(update_fail_htlcs.len(), 1);
1497 update_fail_htlcs[0].clone()
1499 _ => panic!("Unexpected event"),
1501 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1502 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1504 check_added_monitors!(nodes[1], 2);
1508 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1509 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1510 // Set the fee rate for the channel very high, to the point where the fundee
1511 // sending any above-dust amount would result in a channel reserve violation.
1512 // In this test we check that we would be prevented from sending an HTLC in
1514 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1517 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1518 let default_config = UserConfig::default();
1519 let opt_anchors = false;
1521 let mut push_amt = 100_000_000;
1522 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1524 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1526 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1528 // Sending exactly enough to hit the reserve amount should be accepted
1529 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1530 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1533 // However one more HTLC should be significantly over the reserve amount and fail.
1534 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1535 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1536 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1537 ), true, APIError::ChannelUnavailable { ref err },
1538 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1539 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1540 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);
1544 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1545 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1546 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1547 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1548 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1549 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1550 let default_config = UserConfig::default();
1551 let opt_anchors = false;
1553 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1554 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1555 // transaction fee with 0 HTLCs (183 sats)).
1556 let mut push_amt = 100_000_000;
1557 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1558 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1559 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1561 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1562 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1566 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1567 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1568 let secp_ctx = Secp256k1::new();
1569 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1570 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1571 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1572 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1573 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1574 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1575 let msg = msgs::UpdateAddHTLC {
1577 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578 amount_msat: htlc_msat,
1579 payment_hash: payment_hash,
1580 cltv_expiry: htlc_cltv,
1581 onion_routing_packet: onion_packet,
1584 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586 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);
1587 assert_eq!(nodes[0].node.list_channels().len(), 0);
1588 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590 check_added_monitors!(nodes[0], 1);
1591 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() });
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597 // calculating our commitment transaction fee (this was previously broken).
1598 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1601 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604 let default_config = UserConfig::default();
1605 let opt_anchors = false;
1607 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609 // transaction fee with 0 HTLCs (183 sats)).
1610 let mut push_amt = 100_000_000;
1611 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1613 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1615 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619 // commitment transaction fee.
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1622 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1627 // One more than the dust amt should fail, however.
1628 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1630 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1631 ), true, APIError::ChannelUnavailable { ref err },
1632 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1636 fn test_chan_init_feerate_unaffordability() {
1637 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1638 // channel reserve and feerate requirements.
1639 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1640 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1643 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1644 let default_config = UserConfig::default();
1645 let opt_anchors = false;
1647 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1649 let mut push_amt = 100_000_000;
1650 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1651 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1652 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1654 // During open, we don't have a "counterparty channel reserve" to check against, so that
1655 // requirement only comes into play on the open_channel handling side.
1656 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1657 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1658 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1659 open_channel_msg.push_msat += 1;
1660 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1662 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1663 assert_eq!(msg_events.len(), 1);
1664 match msg_events[0] {
1665 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1666 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1668 _ => panic!("Unexpected event"),
1673 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1674 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1675 // calculating our counterparty's commitment transaction fee (this was previously broken).
1676 let chanmon_cfgs = create_chanmon_cfgs(2);
1677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1679 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1682 let payment_amt = 46000; // Dust amount
1683 // In the previous code, these first four payments would succeed.
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1697 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1698 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1699 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1703 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1704 let chanmon_cfgs = create_chanmon_cfgs(3);
1705 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1706 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1707 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1708 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1709 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1712 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1713 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1714 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1715 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1717 // Add a 2* and +1 for the fee spike reserve.
1718 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1719 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;
1720 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1722 // Add a pending HTLC.
1723 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1724 let payment_event_1 = {
1725 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1726 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1727 check_added_monitors!(nodes[0], 1);
1729 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1730 assert_eq!(events.len(), 1);
1731 SendEvent::from_event(events.remove(0))
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1735 // Attempt to trigger a channel reserve violation --> payment failure.
1736 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1737 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;
1738 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1739 let mut route_2 = route_1.clone();
1740 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1742 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1743 let secp_ctx = Secp256k1::new();
1744 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1745 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1746 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1747 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1748 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1749 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1750 let msg = msgs::UpdateAddHTLC {
1753 amount_msat: htlc_msat + 1,
1754 payment_hash: our_payment_hash_1,
1755 cltv_expiry: htlc_cltv,
1756 onion_routing_packet: onion_packet,
1759 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1760 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1761 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1762 assert_eq!(nodes[1].node.list_channels().len(), 1);
1763 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1764 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1765 check_added_monitors!(nodes[1], 1);
1766 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1770 fn test_inbound_outbound_capacity_is_not_zero() {
1771 let chanmon_cfgs = create_chanmon_cfgs(2);
1772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1774 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1775 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1776 let channels0 = node_chanmgrs[0].list_channels();
1777 let channels1 = node_chanmgrs[1].list_channels();
1778 let default_config = UserConfig::default();
1779 assert_eq!(channels0.len(), 1);
1780 assert_eq!(channels1.len(), 1);
1782 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1783 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1784 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1786 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1787 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1790 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1791 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1795 fn test_channel_reserve_holding_cell_htlcs() {
1796 let chanmon_cfgs = create_chanmon_cfgs(3);
1797 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1798 // When this test was written, the default base fee floated based on the HTLC count.
1799 // It is now fixed, so we simply set the fee to the expected value here.
1800 let mut config = test_default_channel_config();
1801 config.channel_config.forwarding_fee_base_msat = 239;
1802 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1803 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1804 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1805 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1807 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1808 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1810 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1811 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1813 macro_rules! expect_forward {
1815 let mut events = $node.node.get_and_clear_pending_msg_events();
1816 assert_eq!(events.len(), 1);
1817 check_added_monitors!($node, 1);
1818 let payment_event = SendEvent::from_event(events.remove(0));
1823 let feemsat = 239; // set above
1824 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1825 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1826 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1828 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1830 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1832 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1833 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1834 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1835 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1836 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1838 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1839 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1840 ), true, APIError::ChannelUnavailable { ref err },
1841 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)));
1842 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1843 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);
1846 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1847 // nodes[0]'s wealth
1849 let amt_msat = recv_value_0 + total_fee_msat;
1850 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1851 // Also, ensure that each payment has enough to be over the dust limit to
1852 // ensure it'll be included in each commit tx fee calculation.
1853 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1854 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1855 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1859 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1860 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1861 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1862 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1863 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1865 let (stat01_, stat11_, stat12_, stat22_) = (
1866 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1867 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1868 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1869 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1872 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1873 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1874 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1875 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1876 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1879 // adding pending output.
1880 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1881 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1882 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1883 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1884 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1885 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1886 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1887 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1888 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1890 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1891 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1892 let amt_msat_1 = recv_value_1 + total_fee_msat;
1894 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);
1895 let payment_event_1 = {
1896 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1897 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1898 check_added_monitors!(nodes[0], 1);
1900 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1901 assert_eq!(events.len(), 1);
1902 SendEvent::from_event(events.remove(0))
1904 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1906 // channel reserve test with htlc pending output > 0
1907 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1909 let mut route = route_1.clone();
1910 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1911 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1912 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1913 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1914 ), true, APIError::ChannelUnavailable { ref err },
1915 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1916 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919 // split the rest to test holding cell
1920 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1921 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1922 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1923 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1925 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1926 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);
1929 // now see if they go through on both sides
1930 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);
1931 // but this will stuck in the holding cell
1932 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1933 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1934 check_added_monitors!(nodes[0], 0);
1935 let events = nodes[0].node.get_and_clear_pending_events();
1936 assert_eq!(events.len(), 0);
1938 // test with outbound holding cell amount > 0
1940 let (mut route, our_payment_hash, _, our_payment_secret) =
1941 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1942 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1943 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1944 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1945 ), true, APIError::ChannelUnavailable { ref err },
1946 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1947 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1948 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1951 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);
1952 // this will also stuck in the holding cell
1953 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1954 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1955 check_added_monitors!(nodes[0], 0);
1956 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1957 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1959 // flush the pending htlc
1960 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1961 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1962 check_added_monitors!(nodes[1], 1);
1964 // the pending htlc should be promoted to committed
1965 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1966 check_added_monitors!(nodes[0], 1);
1967 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1969 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1970 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1971 // No commitment_signed so get_event_msg's assert(len == 1) passes
1972 check_added_monitors!(nodes[0], 1);
1974 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1975 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1976 check_added_monitors!(nodes[1], 1);
1978 expect_pending_htlcs_forwardable!(nodes[1]);
1980 let ref payment_event_11 = expect_forward!(nodes[1]);
1981 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1982 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1984 expect_pending_htlcs_forwardable!(nodes[2]);
1985 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1987 // flush the htlcs in the holding cell
1988 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1989 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1990 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1991 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1992 expect_pending_htlcs_forwardable!(nodes[1]);
1994 let ref payment_event_3 = expect_forward!(nodes[1]);
1995 assert_eq!(payment_event_3.msgs.len(), 2);
1996 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1997 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1999 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2000 expect_pending_htlcs_forwardable!(nodes[2]);
2002 let events = nodes[2].node.get_and_clear_pending_events();
2003 assert_eq!(events.len(), 2);
2005 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2006 assert_eq!(our_payment_hash_21, *payment_hash);
2007 assert_eq!(recv_value_21, amount_msat);
2008 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2009 assert_eq!(via_channel_id, Some(chan_2.2));
2011 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2012 assert!(payment_preimage.is_none());
2013 assert_eq!(our_payment_secret_21, *payment_secret);
2015 _ => panic!("expected PaymentPurpose::InvoicePayment")
2018 _ => panic!("Unexpected event"),
2021 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2022 assert_eq!(our_payment_hash_22, *payment_hash);
2023 assert_eq!(recv_value_22, amount_msat);
2024 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2025 assert_eq!(via_channel_id, Some(chan_2.2));
2027 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2028 assert!(payment_preimage.is_none());
2029 assert_eq!(our_payment_secret_22, *payment_secret);
2031 _ => panic!("expected PaymentPurpose::InvoicePayment")
2034 _ => panic!("Unexpected event"),
2037 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2038 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2039 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2041 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2042 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2043 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2045 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2046 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);
2047 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2048 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2049 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2051 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2052 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2056 fn channel_reserve_in_flight_removes() {
2057 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2058 // can send to its counterparty, but due to update ordering, the other side may not yet have
2059 // considered those HTLCs fully removed.
2060 // This tests that we don't count HTLCs which will not be included in the next remote
2061 // commitment transaction towards the reserve value (as it implies no commitment transaction
2062 // will be generated which violates the remote reserve value).
2063 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2065 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2066 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2067 // you only consider the value of the first HTLC, it may not),
2068 // * start routing a third HTLC from A to B,
2069 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2070 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2071 // * deliver the first fulfill from B
2072 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2074 // * deliver A's response CS and RAA.
2075 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2076 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2077 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2078 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2079 let chanmon_cfgs = create_chanmon_cfgs(2);
2080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2082 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2083 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2085 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2086 // Route the first two HTLCs.
2087 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2088 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2089 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2091 // Start routing the third HTLC (this is just used to get everyone in the right state).
2092 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2094 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2095 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2096 check_added_monitors!(nodes[0], 1);
2097 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2098 assert_eq!(events.len(), 1);
2099 SendEvent::from_event(events.remove(0))
2102 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2103 // initial fulfill/CS.
2104 nodes[1].node.claim_funds(payment_preimage_1);
2105 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2106 check_added_monitors!(nodes[1], 1);
2107 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2109 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2110 // remove the second HTLC when we send the HTLC back from B to A.
2111 nodes[1].node.claim_funds(payment_preimage_2);
2112 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2113 check_added_monitors!(nodes[1], 1);
2114 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2116 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2117 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2118 check_added_monitors!(nodes[0], 1);
2119 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2120 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2122 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2123 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2124 check_added_monitors!(nodes[1], 1);
2125 // B is already AwaitingRAA, so cant generate a CS here
2126 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2128 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2129 check_added_monitors!(nodes[1], 1);
2130 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2132 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2133 check_added_monitors!(nodes[0], 1);
2134 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2136 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2137 check_added_monitors!(nodes[1], 1);
2138 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2140 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2141 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2142 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2143 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2144 // on-chain as necessary).
2145 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2146 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2147 check_added_monitors!(nodes[0], 1);
2148 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2149 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2151 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2152 check_added_monitors!(nodes[1], 1);
2153 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2155 expect_pending_htlcs_forwardable!(nodes[1]);
2156 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2158 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2159 // resolve the second HTLC from A's point of view.
2160 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2161 check_added_monitors!(nodes[0], 1);
2162 expect_payment_path_successful!(nodes[0]);
2163 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2165 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2166 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2167 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2169 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2170 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2171 check_added_monitors!(nodes[1], 1);
2172 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2173 assert_eq!(events.len(), 1);
2174 SendEvent::from_event(events.remove(0))
2177 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2178 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2179 check_added_monitors!(nodes[0], 1);
2180 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2182 // Now just resolve all the outstanding messages/HTLCs for completeness...
2184 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2185 check_added_monitors!(nodes[1], 1);
2186 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2188 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2189 check_added_monitors!(nodes[1], 1);
2191 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2192 check_added_monitors!(nodes[0], 1);
2193 expect_payment_path_successful!(nodes[0]);
2194 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2196 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2197 check_added_monitors!(nodes[1], 1);
2198 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2200 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2201 check_added_monitors!(nodes[0], 1);
2203 expect_pending_htlcs_forwardable!(nodes[0]);
2204 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2206 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2207 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2211 fn channel_monitor_network_test() {
2212 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2213 // tests that ChannelMonitor is able to recover from various states.
2214 let chanmon_cfgs = create_chanmon_cfgs(5);
2215 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2216 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2217 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2219 // Create some initial channels
2220 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2221 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2222 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2223 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2225 // Make sure all nodes are at the same starting height
2226 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2227 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2228 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2229 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2230 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2232 // Rebalance the network a bit by relaying one payment through all the channels...
2233 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2234 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2235 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2236 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2238 // Simple case with no pending HTLCs:
2239 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2240 check_added_monitors!(nodes[1], 1);
2241 check_closed_broadcast!(nodes[1], true);
2243 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2244 assert_eq!(node_txn.len(), 1);
2245 mine_transaction(&nodes[0], &node_txn[0]);
2246 check_added_monitors!(nodes[0], 1);
2247 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2249 check_closed_broadcast!(nodes[0], true);
2250 assert_eq!(nodes[0].node.list_channels().len(), 0);
2251 assert_eq!(nodes[1].node.list_channels().len(), 1);
2252 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2253 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2255 // One pending HTLC is discarded by the force-close:
2256 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2258 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2259 // broadcasted until we reach the timelock time).
2260 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2261 check_closed_broadcast!(nodes[1], true);
2262 check_added_monitors!(nodes[1], 1);
2264 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2265 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2267 mine_transaction(&nodes[2], &node_txn[0]);
2268 check_added_monitors!(nodes[2], 1);
2269 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2271 check_closed_broadcast!(nodes[2], true);
2272 assert_eq!(nodes[1].node.list_channels().len(), 0);
2273 assert_eq!(nodes[2].node.list_channels().len(), 1);
2274 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2275 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2277 macro_rules! claim_funds {
2278 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2280 $node.node.claim_funds($preimage);
2281 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2282 check_added_monitors!($node, 1);
2284 let events = $node.node.get_and_clear_pending_msg_events();
2285 assert_eq!(events.len(), 1);
2287 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2288 assert!(update_add_htlcs.is_empty());
2289 assert!(update_fail_htlcs.is_empty());
2290 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2292 _ => panic!("Unexpected event"),
2298 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2299 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2300 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2301 check_added_monitors!(nodes[2], 1);
2302 check_closed_broadcast!(nodes[2], true);
2303 let node2_commitment_txid;
2305 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2306 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2307 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2308 node2_commitment_txid = node_txn[0].txid();
2310 // Claim the payment on nodes[3], giving it knowledge of the preimage
2311 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2312 mine_transaction(&nodes[3], &node_txn[0]);
2313 check_added_monitors!(nodes[3], 1);
2314 check_preimage_claim(&nodes[3], &node_txn);
2316 check_closed_broadcast!(nodes[3], true);
2317 assert_eq!(nodes[2].node.list_channels().len(), 0);
2318 assert_eq!(nodes[3].node.list_channels().len(), 1);
2319 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2320 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2322 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2323 // confusing us in the following tests.
2324 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2326 // One pending HTLC to time out:
2327 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2328 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2331 let (close_chan_update_1, close_chan_update_2) = {
2332 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2333 let events = nodes[3].node.get_and_clear_pending_msg_events();
2334 assert_eq!(events.len(), 2);
2335 let close_chan_update_1 = match events[0] {
2336 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2339 _ => panic!("Unexpected event"),
2342 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2343 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2345 _ => panic!("Unexpected event"),
2347 check_added_monitors!(nodes[3], 1);
2349 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2351 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2352 node_txn.retain(|tx| {
2353 if tx.input[0].previous_output.txid == node2_commitment_txid {
2359 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2361 // Claim the payment on nodes[4], giving it knowledge of the preimage
2362 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2364 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2365 let events = nodes[4].node.get_and_clear_pending_msg_events();
2366 assert_eq!(events.len(), 2);
2367 let close_chan_update_2 = match events[0] {
2368 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2371 _ => panic!("Unexpected event"),
2374 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2375 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2377 _ => panic!("Unexpected event"),
2379 check_added_monitors!(nodes[4], 1);
2380 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2382 mine_transaction(&nodes[4], &node_txn[0]);
2383 check_preimage_claim(&nodes[4], &node_txn);
2384 (close_chan_update_1, close_chan_update_2)
2386 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2387 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2388 assert_eq!(nodes[3].node.list_channels().len(), 0);
2389 assert_eq!(nodes[4].node.list_channels().len(), 0);
2391 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2392 ChannelMonitorUpdateStatus::Completed);
2393 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2394 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2398 fn test_justice_tx_htlc_timeout() {
2399 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2400 let mut alice_config = UserConfig::default();
2401 alice_config.channel_handshake_config.announced_channel = true;
2402 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2403 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2404 let mut bob_config = UserConfig::default();
2405 bob_config.channel_handshake_config.announced_channel = true;
2406 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2407 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2408 let user_cfgs = [Some(alice_config), Some(bob_config)];
2409 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2410 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2411 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2414 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2415 // Create some new channels:
2416 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2418 // A pending HTLC which will be revoked:
2419 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2420 // Get the will-be-revoked local txn from nodes[0]
2421 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2422 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2423 assert_eq!(revoked_local_txn[0].input.len(), 1);
2424 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2425 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2426 assert_eq!(revoked_local_txn[1].input.len(), 1);
2427 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2428 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2429 // Revoke the old state
2430 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2433 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2435 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2436 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2437 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2438 check_spends!(node_txn[0], revoked_local_txn[0]);
2439 node_txn.swap_remove(0);
2441 check_added_monitors!(nodes[1], 1);
2442 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2443 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2445 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2446 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2447 // Verify broadcast of revoked HTLC-timeout
2448 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2449 check_added_monitors!(nodes[0], 1);
2450 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2451 // Broadcast revoked HTLC-timeout on node 1
2452 mine_transaction(&nodes[1], &node_txn[1]);
2453 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2455 get_announce_close_broadcast_events(&nodes, 0, 1);
2456 assert_eq!(nodes[0].node.list_channels().len(), 0);
2457 assert_eq!(nodes[1].node.list_channels().len(), 0);
2461 fn test_justice_tx_htlc_success() {
2462 // Test justice txn built on revoked HTLC-Success tx, against both sides
2463 let mut alice_config = UserConfig::default();
2464 alice_config.channel_handshake_config.announced_channel = true;
2465 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2466 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2467 let mut bob_config = UserConfig::default();
2468 bob_config.channel_handshake_config.announced_channel = true;
2469 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2470 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2471 let user_cfgs = [Some(alice_config), Some(bob_config)];
2472 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2473 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2474 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2478 // Create some new channels:
2479 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2481 // A pending HTLC which will be revoked:
2482 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2483 // Get the will-be-revoked local txn from B
2484 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2485 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2486 assert_eq!(revoked_local_txn[0].input.len(), 1);
2487 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2488 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2489 // Revoke the old state
2490 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2492 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2494 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2495 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2496 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2498 check_spends!(node_txn[0], revoked_local_txn[0]);
2499 node_txn.swap_remove(0);
2501 check_added_monitors!(nodes[0], 1);
2502 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2504 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2505 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2506 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2507 check_added_monitors!(nodes[1], 1);
2508 mine_transaction(&nodes[0], &node_txn[1]);
2509 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2510 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2512 get_announce_close_broadcast_events(&nodes, 0, 1);
2513 assert_eq!(nodes[0].node.list_channels().len(), 0);
2514 assert_eq!(nodes[1].node.list_channels().len(), 0);
2518 fn revoked_output_claim() {
2519 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2520 // transaction is broadcast by its counterparty
2521 let chanmon_cfgs = create_chanmon_cfgs(2);
2522 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2523 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2524 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2525 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2526 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2527 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2528 assert_eq!(revoked_local_txn.len(), 1);
2529 // Only output is the full channel value back to nodes[0]:
2530 assert_eq!(revoked_local_txn[0].output.len(), 1);
2531 // Send a payment through, updating everyone's latest commitment txn
2532 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2534 // Inform nodes[1] that nodes[0] broadcast a stale tx
2535 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2536 check_added_monitors!(nodes[1], 1);
2537 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2538 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2539 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2541 check_spends!(node_txn[0], revoked_local_txn[0]);
2543 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2544 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2545 get_announce_close_broadcast_events(&nodes, 0, 1);
2546 check_added_monitors!(nodes[0], 1);
2547 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2551 fn claim_htlc_outputs_shared_tx() {
2552 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2553 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2554 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2557 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2559 // Create some new channel:
2560 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2562 // Rebalance the network to generate htlc in the two directions
2563 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2564 // 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
2565 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2566 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2568 // Get the will-be-revoked local txn from node[0]
2569 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2570 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2571 assert_eq!(revoked_local_txn[0].input.len(), 1);
2572 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2573 assert_eq!(revoked_local_txn[1].input.len(), 1);
2574 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2575 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2576 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2578 //Revoke the old state
2579 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2582 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2583 check_added_monitors!(nodes[0], 1);
2584 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2585 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2586 check_added_monitors!(nodes[1], 1);
2587 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2588 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2589 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2591 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2592 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2594 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2595 check_spends!(node_txn[0], revoked_local_txn[0]);
2597 let mut witness_lens = BTreeSet::new();
2598 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2599 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2600 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2601 assert_eq!(witness_lens.len(), 3);
2602 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2603 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2604 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2606 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2607 // ANTI_REORG_DELAY confirmations.
2608 mine_transaction(&nodes[1], &node_txn[0]);
2609 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2610 expect_payment_failed!(nodes[1], payment_hash_2, false);
2612 get_announce_close_broadcast_events(&nodes, 0, 1);
2613 assert_eq!(nodes[0].node.list_channels().len(), 0);
2614 assert_eq!(nodes[1].node.list_channels().len(), 0);
2618 fn claim_htlc_outputs_single_tx() {
2619 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2620 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2621 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2624 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2626 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2628 // Rebalance the network to generate htlc in the two directions
2629 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2630 // 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
2631 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2632 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2633 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2635 // Get the will-be-revoked local txn from node[0]
2636 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2638 //Revoke the old state
2639 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2642 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2643 check_added_monitors!(nodes[0], 1);
2644 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2645 check_added_monitors!(nodes[1], 1);
2646 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2647 let mut events = nodes[0].node.get_and_clear_pending_events();
2648 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2649 match events.last().unwrap() {
2650 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2651 _ => panic!("Unexpected event"),
2654 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2655 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2657 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2659 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2660 assert_eq!(node_txn[0].input.len(), 1);
2661 check_spends!(node_txn[0], chan_1.3);
2662 assert_eq!(node_txn[1].input.len(), 1);
2663 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2664 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2665 check_spends!(node_txn[1], node_txn[0]);
2667 // Filter out any non justice transactions.
2668 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2669 assert!(node_txn.len() > 3);
2671 assert_eq!(node_txn[0].input.len(), 1);
2672 assert_eq!(node_txn[1].input.len(), 1);
2673 assert_eq!(node_txn[2].input.len(), 1);
2675 check_spends!(node_txn[0], revoked_local_txn[0]);
2676 check_spends!(node_txn[1], revoked_local_txn[0]);
2677 check_spends!(node_txn[2], revoked_local_txn[0]);
2679 let mut witness_lens = BTreeSet::new();
2680 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2681 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2682 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2683 assert_eq!(witness_lens.len(), 3);
2684 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2685 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2686 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2688 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2689 // ANTI_REORG_DELAY confirmations.
2690 mine_transaction(&nodes[1], &node_txn[0]);
2691 mine_transaction(&nodes[1], &node_txn[1]);
2692 mine_transaction(&nodes[1], &node_txn[2]);
2693 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694 expect_payment_failed!(nodes[1], payment_hash_2, false);
2696 get_announce_close_broadcast_events(&nodes, 0, 1);
2697 assert_eq!(nodes[0].node.list_channels().len(), 0);
2698 assert_eq!(nodes[1].node.list_channels().len(), 0);
2702 fn test_htlc_on_chain_success() {
2703 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2704 // the preimage backward accordingly. So here we test that ChannelManager is
2705 // broadcasting the right event to other nodes in payment path.
2706 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2707 // A --------------------> B ----------------------> C (preimage)
2708 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2709 // commitment transaction was broadcast.
2710 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2712 // B should be able to claim via preimage if A then broadcasts its local tx.
2713 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2714 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2715 // PaymentSent event).
2717 let chanmon_cfgs = create_chanmon_cfgs(3);
2718 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2719 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2720 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2722 // Create some initial channels
2723 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2724 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2726 // Ensure all nodes are at the same height
2727 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2728 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2729 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2730 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2732 // Rebalance the network a bit by relaying one payment through all the channels...
2733 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2734 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2736 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2737 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2739 // Broadcast legit commitment tx from C on B's chain
2740 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2741 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2742 assert_eq!(commitment_tx.len(), 1);
2743 check_spends!(commitment_tx[0], chan_2.3);
2744 nodes[2].node.claim_funds(our_payment_preimage);
2745 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2746 nodes[2].node.claim_funds(our_payment_preimage_2);
2747 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2748 check_added_monitors!(nodes[2], 2);
2749 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2750 assert!(updates.update_add_htlcs.is_empty());
2751 assert!(updates.update_fail_htlcs.is_empty());
2752 assert!(updates.update_fail_malformed_htlcs.is_empty());
2753 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2755 mine_transaction(&nodes[2], &commitment_tx[0]);
2756 check_closed_broadcast!(nodes[2], true);
2757 check_added_monitors!(nodes[2], 1);
2758 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2759 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2760 assert_eq!(node_txn.len(), 2);
2761 check_spends!(node_txn[0], commitment_tx[0]);
2762 check_spends!(node_txn[1], commitment_tx[0]);
2763 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2764 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2765 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2766 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2767 assert_eq!(node_txn[0].lock_time.0, 0);
2768 assert_eq!(node_txn[1].lock_time.0, 0);
2770 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2771 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()]));
2772 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2774 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2775 assert_eq!(added_monitors.len(), 1);
2776 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2777 added_monitors.clear();
2779 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2780 assert_eq!(forwarded_events.len(), 3);
2781 match forwarded_events[0] {
2782 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2783 _ => panic!("Unexpected event"),
2785 let chan_id = Some(chan_1.2);
2786 match forwarded_events[1] {
2787 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2788 assert_eq!(fee_earned_msat, Some(1000));
2789 assert_eq!(prev_channel_id, chan_id);
2790 assert_eq!(claim_from_onchain_tx, true);
2791 assert_eq!(next_channel_id, Some(chan_2.2));
2792 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2796 match forwarded_events[2] {
2797 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2798 assert_eq!(fee_earned_msat, Some(1000));
2799 assert_eq!(prev_channel_id, chan_id);
2800 assert_eq!(claim_from_onchain_tx, true);
2801 assert_eq!(next_channel_id, Some(chan_2.2));
2802 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2806 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2808 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2809 assert_eq!(added_monitors.len(), 2);
2810 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2811 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2812 added_monitors.clear();
2814 assert_eq!(events.len(), 3);
2816 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2817 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2819 match nodes_2_event {
2820 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2821 _ => panic!("Unexpected event"),
2824 match nodes_0_event {
2825 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, .. } } => {
2826 assert!(update_add_htlcs.is_empty());
2827 assert!(update_fail_htlcs.is_empty());
2828 assert_eq!(update_fulfill_htlcs.len(), 1);
2829 assert!(update_fail_malformed_htlcs.is_empty());
2830 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2832 _ => panic!("Unexpected event"),
2835 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2837 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2838 _ => panic!("Unexpected event"),
2841 macro_rules! check_tx_local_broadcast {
2842 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2843 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2844 assert_eq!(node_txn.len(), 2);
2845 // Node[1]: 2 * HTLC-timeout tx
2846 // Node[0]: 2 * HTLC-timeout tx
2847 check_spends!(node_txn[0], $commitment_tx);
2848 check_spends!(node_txn[1], $commitment_tx);
2849 assert_ne!(node_txn[0].lock_time.0, 0);
2850 assert_ne!(node_txn[1].lock_time.0, 0);
2852 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2854 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2855 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2857 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2858 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2859 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2860 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2865 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2866 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2868 // Broadcast legit commitment tx from A on B's chain
2869 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2870 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2871 check_spends!(node_a_commitment_tx[0], chan_1.3);
2872 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2873 check_closed_broadcast!(nodes[1], true);
2874 check_added_monitors!(nodes[1], 1);
2875 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2876 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2877 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2878 let commitment_spend =
2879 if node_txn.len() == 1 {
2882 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2883 // FullBlockViaListen
2884 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2885 check_spends!(node_txn[1], commitment_tx[0]);
2886 check_spends!(node_txn[2], commitment_tx[0]);
2887 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2890 check_spends!(node_txn[0], commitment_tx[0]);
2891 check_spends!(node_txn[1], commitment_tx[0]);
2892 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2897 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2898 assert_eq!(commitment_spend.input.len(), 2);
2899 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2900 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2901 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2902 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2903 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2904 // we already checked the same situation with A.
2906 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2907 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2908 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2909 check_closed_broadcast!(nodes[0], true);
2910 check_added_monitors!(nodes[0], 1);
2911 let events = nodes[0].node.get_and_clear_pending_events();
2912 assert_eq!(events.len(), 5);
2913 let mut first_claimed = false;
2914 for event in events {
2916 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2917 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2918 assert!(!first_claimed);
2919 first_claimed = true;
2921 assert_eq!(payment_preimage, our_payment_preimage_2);
2922 assert_eq!(payment_hash, payment_hash_2);
2925 Event::PaymentPathSuccessful { .. } => {},
2926 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2927 _ => panic!("Unexpected event"),
2930 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2933 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2934 // Test that in case of a unilateral close onchain, we detect the state of output and
2935 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2936 // broadcasting the right event to other nodes in payment path.
2937 // A ------------------> B ----------------------> C (timeout)
2938 // B's commitment tx C's commitment tx
2940 // B's HTLC timeout tx B's timeout tx
2942 let chanmon_cfgs = create_chanmon_cfgs(3);
2943 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2944 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2945 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2946 *nodes[0].connect_style.borrow_mut() = connect_style;
2947 *nodes[1].connect_style.borrow_mut() = connect_style;
2948 *nodes[2].connect_style.borrow_mut() = connect_style;
2950 // Create some intial channels
2951 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2952 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2954 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2955 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2956 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2958 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2960 // Broadcast legit commitment tx from C on B's chain
2961 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2962 check_spends!(commitment_tx[0], chan_2.3);
2963 nodes[2].node.fail_htlc_backwards(&payment_hash);
2964 check_added_monitors!(nodes[2], 0);
2965 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2966 check_added_monitors!(nodes[2], 1);
2968 let events = nodes[2].node.get_and_clear_pending_msg_events();
2969 assert_eq!(events.len(), 1);
2971 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, .. } } => {
2972 assert!(update_add_htlcs.is_empty());
2973 assert!(!update_fail_htlcs.is_empty());
2974 assert!(update_fulfill_htlcs.is_empty());
2975 assert!(update_fail_malformed_htlcs.is_empty());
2976 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2978 _ => panic!("Unexpected event"),
2980 mine_transaction(&nodes[2], &commitment_tx[0]);
2981 check_closed_broadcast!(nodes[2], true);
2982 check_added_monitors!(nodes[2], 1);
2983 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2984 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2985 assert_eq!(node_txn.len(), 0);
2987 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2988 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2989 mine_transaction(&nodes[1], &commitment_tx[0]);
2990 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2991 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2993 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2994 if nodes[1].connect_style.borrow().skips_blocks() {
2995 assert_eq!(txn.len(), 1);
2997 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2999 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3000 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3004 mine_transaction(&nodes[1], &timeout_tx);
3005 check_added_monitors!(nodes[1], 1);
3006 check_closed_broadcast!(nodes[1], true);
3008 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3010 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 }]);
3011 check_added_monitors!(nodes[1], 1);
3012 let events = nodes[1].node.get_and_clear_pending_msg_events();
3013 assert_eq!(events.len(), 1);
3015 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, .. } } => {
3016 assert!(update_add_htlcs.is_empty());
3017 assert!(!update_fail_htlcs.is_empty());
3018 assert!(update_fulfill_htlcs.is_empty());
3019 assert!(update_fail_malformed_htlcs.is_empty());
3020 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3022 _ => panic!("Unexpected event"),
3025 // Broadcast legit commitment tx from B on A's chain
3026 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3027 check_spends!(commitment_tx[0], chan_1.3);
3029 mine_transaction(&nodes[0], &commitment_tx[0]);
3030 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3032 check_closed_broadcast!(nodes[0], true);
3033 check_added_monitors!(nodes[0], 1);
3034 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3035 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3036 assert_eq!(node_txn.len(), 1);
3037 check_spends!(node_txn[0], commitment_tx[0]);
3038 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3042 fn test_htlc_on_chain_timeout() {
3043 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3044 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3045 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3049 fn test_simple_commitment_revoked_fail_backward() {
3050 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3051 // and fail backward accordingly.
3053 let chanmon_cfgs = create_chanmon_cfgs(3);
3054 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3055 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3056 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3058 // Create some initial channels
3059 create_announced_chan_between_nodes(&nodes, 0, 1);
3060 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3062 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063 // Get the will-be-revoked local txn from nodes[2]
3064 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3065 // Revoke the old state
3066 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3068 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3070 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3071 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3072 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3073 check_added_monitors!(nodes[1], 1);
3074 check_closed_broadcast!(nodes[1], true);
3076 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 }]);
3077 check_added_monitors!(nodes[1], 1);
3078 let events = nodes[1].node.get_and_clear_pending_msg_events();
3079 assert_eq!(events.len(), 1);
3081 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, .. } } => {
3082 assert!(update_add_htlcs.is_empty());
3083 assert_eq!(update_fail_htlcs.len(), 1);
3084 assert!(update_fulfill_htlcs.is_empty());
3085 assert!(update_fail_malformed_htlcs.is_empty());
3086 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3088 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3089 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3090 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3092 _ => panic!("Unexpected event"),
3096 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3097 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3098 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3099 // commitment transaction anymore.
3100 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3101 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3102 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3103 // technically disallowed and we should probably handle it reasonably.
3104 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3105 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3107 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3108 // commitment_signed (implying it will be in the latest remote commitment transaction).
3109 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3110 // and once they revoke the previous commitment transaction (allowing us to send a new
3111 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3112 let chanmon_cfgs = create_chanmon_cfgs(3);
3113 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3114 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3115 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3117 // Create some initial channels
3118 create_announced_chan_between_nodes(&nodes, 0, 1);
3119 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3121 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 });
3122 // Get the will-be-revoked local txn from nodes[2]
3123 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3124 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3125 // Revoke the old state
3126 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3128 let value = if use_dust {
3129 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3130 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3131 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3132 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3135 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3136 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3137 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3139 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3140 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3141 check_added_monitors!(nodes[2], 1);
3142 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3143 assert!(updates.update_add_htlcs.is_empty());
3144 assert!(updates.update_fulfill_htlcs.is_empty());
3145 assert!(updates.update_fail_malformed_htlcs.is_empty());
3146 assert_eq!(updates.update_fail_htlcs.len(), 1);
3147 assert!(updates.update_fee.is_none());
3148 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3149 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3150 // Drop the last RAA from 3 -> 2
3152 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3153 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3154 check_added_monitors!(nodes[2], 1);
3155 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3156 assert!(updates.update_add_htlcs.is_empty());
3157 assert!(updates.update_fulfill_htlcs.is_empty());
3158 assert!(updates.update_fail_malformed_htlcs.is_empty());
3159 assert_eq!(updates.update_fail_htlcs.len(), 1);
3160 assert!(updates.update_fee.is_none());
3161 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3162 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3163 check_added_monitors!(nodes[1], 1);
3164 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3165 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3166 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3167 check_added_monitors!(nodes[2], 1);
3169 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3170 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3171 check_added_monitors!(nodes[2], 1);
3172 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173 assert!(updates.update_add_htlcs.is_empty());
3174 assert!(updates.update_fulfill_htlcs.is_empty());
3175 assert!(updates.update_fail_malformed_htlcs.is_empty());
3176 assert_eq!(updates.update_fail_htlcs.len(), 1);
3177 assert!(updates.update_fee.is_none());
3178 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3179 // At this point first_payment_hash has dropped out of the latest two commitment
3180 // transactions that nodes[1] is tracking...
3181 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3182 check_added_monitors!(nodes[1], 1);
3183 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3184 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3185 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3186 check_added_monitors!(nodes[2], 1);
3188 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3189 // on nodes[2]'s RAA.
3190 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3191 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3192 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3193 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3194 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3195 check_added_monitors!(nodes[1], 0);
3198 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3199 // One monitor for the new revocation preimage, no second on as we won't generate a new
3200 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3201 check_added_monitors!(nodes[1], 1);
3202 let events = nodes[1].node.get_and_clear_pending_events();
3203 assert_eq!(events.len(), 2);
3205 Event::PendingHTLCsForwardable { .. } => { },
3206 _ => panic!("Unexpected event"),
3209 Event::HTLCHandlingFailed { .. } => { },
3210 _ => panic!("Unexpected event"),
3212 // Deliberately don't process the pending fail-back so they all fail back at once after
3213 // block connection just like the !deliver_bs_raa case
3216 let mut failed_htlcs = HashSet::new();
3217 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3219 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3220 check_added_monitors!(nodes[1], 1);
3221 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3223 let events = nodes[1].node.get_and_clear_pending_events();
3224 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3226 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3227 _ => panic!("Unexepected event"),
3230 Event::PaymentPathFailed { ref payment_hash, .. } => {
3231 assert_eq!(*payment_hash, fourth_payment_hash);
3233 _ => panic!("Unexpected event"),
3236 Event::PaymentFailed { ref payment_hash, .. } => {
3237 assert_eq!(*payment_hash, fourth_payment_hash);
3239 _ => panic!("Unexpected event"),
3242 nodes[1].node.process_pending_htlc_forwards();
3243 check_added_monitors!(nodes[1], 1);
3245 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3246 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3249 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3250 match nodes_2_event {
3251 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, .. } } => {
3252 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3253 assert_eq!(update_add_htlcs.len(), 1);
3254 assert!(update_fulfill_htlcs.is_empty());
3255 assert!(update_fail_htlcs.is_empty());
3256 assert!(update_fail_malformed_htlcs.is_empty());
3258 _ => panic!("Unexpected event"),
3262 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3263 match nodes_2_event {
3264 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3265 assert_eq!(channel_id, chan_2.2);
3266 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3268 _ => panic!("Unexpected event"),
3271 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3272 match nodes_0_event {
3273 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, .. } } => {
3274 assert!(update_add_htlcs.is_empty());
3275 assert_eq!(update_fail_htlcs.len(), 3);
3276 assert!(update_fulfill_htlcs.is_empty());
3277 assert!(update_fail_malformed_htlcs.is_empty());
3278 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3280 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3281 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3282 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3284 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3286 let events = nodes[0].node.get_and_clear_pending_events();
3287 assert_eq!(events.len(), 6);
3289 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3290 assert!(failed_htlcs.insert(payment_hash.0));
3291 // If we delivered B's RAA we got an unknown preimage error, not something
3292 // that we should update our routing table for.
3293 if !deliver_bs_raa {
3294 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3297 _ => panic!("Unexpected event"),
3300 Event::PaymentFailed { ref payment_hash, .. } => {
3301 assert_eq!(*payment_hash, first_payment_hash);
3303 _ => panic!("Unexpected event"),
3306 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3307 assert!(failed_htlcs.insert(payment_hash.0));
3309 _ => panic!("Unexpected event"),
3312 Event::PaymentFailed { ref payment_hash, .. } => {
3313 assert_eq!(*payment_hash, second_payment_hash);
3315 _ => panic!("Unexpected event"),
3318 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3319 assert!(failed_htlcs.insert(payment_hash.0));
3321 _ => panic!("Unexpected event"),
3324 Event::PaymentFailed { ref payment_hash, .. } => {
3325 assert_eq!(*payment_hash, third_payment_hash);
3327 _ => panic!("Unexpected event"),
3330 _ => panic!("Unexpected event"),
3333 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3335 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3336 _ => panic!("Unexpected event"),
3339 assert!(failed_htlcs.contains(&first_payment_hash.0));
3340 assert!(failed_htlcs.contains(&second_payment_hash.0));
3341 assert!(failed_htlcs.contains(&third_payment_hash.0));
3345 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3346 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3347 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3348 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3349 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3353 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3354 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3355 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3356 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3357 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3361 fn fail_backward_pending_htlc_upon_channel_failure() {
3362 let chanmon_cfgs = create_chanmon_cfgs(2);
3363 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3364 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3365 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3366 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3368 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3370 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3371 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3372 PaymentId(payment_hash.0)).unwrap();
3373 check_added_monitors!(nodes[0], 1);
3375 let payment_event = {
3376 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3377 assert_eq!(events.len(), 1);
3378 SendEvent::from_event(events.remove(0))
3380 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3381 assert_eq!(payment_event.msgs.len(), 1);
3384 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3385 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3387 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3388 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3389 check_added_monitors!(nodes[0], 0);
3391 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3394 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3396 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3398 let secp_ctx = Secp256k1::new();
3399 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3400 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3401 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3402 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3403 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3404 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3406 // Send a 0-msat update_add_htlc to fail the channel.
3407 let update_add_htlc = msgs::UpdateAddHTLC {
3413 onion_routing_packet,
3415 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3417 let events = nodes[0].node.get_and_clear_pending_events();
3418 assert_eq!(events.len(), 3);
3419 // Check that Alice fails backward the pending HTLC from the second payment.
3421 Event::PaymentPathFailed { payment_hash, .. } => {
3422 assert_eq!(payment_hash, failed_payment_hash);
3424 _ => panic!("Unexpected event"),
3427 Event::PaymentFailed { payment_hash, .. } => {
3428 assert_eq!(payment_hash, failed_payment_hash);
3430 _ => panic!("Unexpected event"),
3433 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3434 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3436 _ => panic!("Unexpected event {:?}", events[1]),
3438 check_closed_broadcast!(nodes[0], true);
3439 check_added_monitors!(nodes[0], 1);
3443 fn test_htlc_ignore_latest_remote_commitment() {
3444 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3445 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3446 let chanmon_cfgs = create_chanmon_cfgs(2);
3447 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3449 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3450 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3451 // We rely on the ability to connect a block redundantly, which isn't allowed via
3452 // `chain::Listen`, so we never run the test if we randomly get assigned that
3456 create_announced_chan_between_nodes(&nodes, 0, 1);
3458 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3459 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3460 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3461 check_closed_broadcast!(nodes[0], true);
3462 check_added_monitors!(nodes[0], 1);
3463 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3465 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3466 assert_eq!(node_txn.len(), 3);
3467 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3469 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3470 connect_block(&nodes[1], &block);
3471 check_closed_broadcast!(nodes[1], true);
3472 check_added_monitors!(nodes[1], 1);
3473 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3475 // Duplicate the connect_block call since this may happen due to other listeners
3476 // registering new transactions
3477 connect_block(&nodes[1], &block);
3481 fn test_force_close_fail_back() {
3482 // Check which HTLCs are failed-backwards on channel force-closure
3483 let chanmon_cfgs = create_chanmon_cfgs(3);
3484 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3485 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3486 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3487 create_announced_chan_between_nodes(&nodes, 0, 1);
3488 create_announced_chan_between_nodes(&nodes, 1, 2);
3490 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3492 let mut payment_event = {
3493 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3494 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3495 check_added_monitors!(nodes[0], 1);
3497 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3498 assert_eq!(events.len(), 1);
3499 SendEvent::from_event(events.remove(0))
3502 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3503 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3505 expect_pending_htlcs_forwardable!(nodes[1]);
3507 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3508 assert_eq!(events_2.len(), 1);
3509 payment_event = SendEvent::from_event(events_2.remove(0));
3510 assert_eq!(payment_event.msgs.len(), 1);
3512 check_added_monitors!(nodes[1], 1);
3513 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3514 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3515 check_added_monitors!(nodes[2], 1);
3516 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3518 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3519 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3520 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3522 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3523 check_closed_broadcast!(nodes[2], true);
3524 check_added_monitors!(nodes[2], 1);
3525 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3527 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3528 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3529 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3530 // back to nodes[1] upon timeout otherwise.
3531 assert_eq!(node_txn.len(), 1);
3535 mine_transaction(&nodes[1], &tx);
3537 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3538 check_closed_broadcast!(nodes[1], true);
3539 check_added_monitors!(nodes[1], 1);
3540 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3542 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3544 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3545 .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);
3547 mine_transaction(&nodes[2], &tx);
3548 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3549 assert_eq!(node_txn.len(), 1);
3550 assert_eq!(node_txn[0].input.len(), 1);
3551 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3552 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3553 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3555 check_spends!(node_txn[0], tx);
3559 fn test_dup_events_on_peer_disconnect() {
3560 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3561 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3562 // as we used to generate the event immediately upon receipt of the payment preimage in the
3563 // update_fulfill_htlc message.
3565 let chanmon_cfgs = create_chanmon_cfgs(2);
3566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3568 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3569 create_announced_chan_between_nodes(&nodes, 0, 1);
3571 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3573 nodes[1].node.claim_funds(payment_preimage);
3574 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3575 check_added_monitors!(nodes[1], 1);
3576 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3577 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3578 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3583 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584 expect_payment_path_successful!(nodes[0]);
3588 fn test_peer_disconnected_before_funding_broadcasted() {
3589 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3590 // before the funding transaction has been broadcasted.
3591 let chanmon_cfgs = create_chanmon_cfgs(2);
3592 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3593 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3594 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3596 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3597 // broadcasted, even though it's created by `nodes[0]`.
3598 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();
3599 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3600 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3601 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3602 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3604 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3605 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3607 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3609 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3610 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3612 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3613 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3616 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3619 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3620 // disconnected before the funding transaction was broadcasted.
3621 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3622 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3624 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3625 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3629 fn test_simple_peer_disconnect() {
3630 // Test that we can reconnect when there are no lost messages
3631 let chanmon_cfgs = create_chanmon_cfgs(3);
3632 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3633 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3634 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3635 create_announced_chan_between_nodes(&nodes, 0, 1);
3636 create_announced_chan_between_nodes(&nodes, 1, 2);
3638 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], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3642 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3643 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3644 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3645 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_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());
3649 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3651 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3652 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3653 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3654 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3656 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3657 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3659 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3660 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3662 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3664 let events = nodes[0].node.get_and_clear_pending_events();
3665 assert_eq!(events.len(), 4);
3667 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3668 assert_eq!(payment_preimage, payment_preimage_3);
3669 assert_eq!(payment_hash, payment_hash_3);
3671 _ => panic!("Unexpected event"),
3674 Event::PaymentPathSuccessful { .. } => {},
3675 _ => panic!("Unexpected event"),
3678 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3679 assert_eq!(payment_hash, payment_hash_5);
3680 assert!(payment_failed_permanently);
3682 _ => panic!("Unexpected event"),
3685 Event::PaymentFailed { payment_hash, .. } => {
3686 assert_eq!(payment_hash, payment_hash_5);
3688 _ => panic!("Unexpected event"),
3692 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3693 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3696 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3697 // Test that we can reconnect when in-flight HTLC updates get dropped
3698 let chanmon_cfgs = create_chanmon_cfgs(2);
3699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3701 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3703 let mut as_channel_ready = None;
3704 let channel_id = if messages_delivered == 0 {
3705 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3706 as_channel_ready = Some(channel_ready);
3707 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3708 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3709 // it before the channel_reestablish message.
3712 create_announced_chan_between_nodes(&nodes, 0, 1).2
3715 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3717 let payment_event = {
3718 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3719 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3720 check_added_monitors!(nodes[0], 1);
3722 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3723 assert_eq!(events.len(), 1);
3724 SendEvent::from_event(events.remove(0))
3726 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3728 if messages_delivered < 2 {
3729 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3731 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3732 if messages_delivered >= 3 {
3733 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3734 check_added_monitors!(nodes[1], 1);
3735 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3737 if messages_delivered >= 4 {
3738 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3739 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3740 check_added_monitors!(nodes[0], 1);
3742 if messages_delivered >= 5 {
3743 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3744 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3745 // No commitment_signed so get_event_msg's assert(len == 1) passes
3746 check_added_monitors!(nodes[0], 1);
3748 if messages_delivered >= 6 {
3749 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3750 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3751 check_added_monitors!(nodes[1], 1);
3758 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3759 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3760 if messages_delivered < 3 {
3761 if simulate_broken_lnd {
3762 // lnd has a long-standing bug where they send a channel_ready prior to a
3763 // channel_reestablish if you reconnect prior to channel_ready time.
3765 // Here we simulate that behavior, delivering a channel_ready immediately on
3766 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3767 // in `reconnect_nodes` but we currently don't fail based on that.
3769 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3770 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3772 // Even if the channel_ready messages get exchanged, as long as nothing further was
3773 // received on either side, both sides will need to resend them.
3774 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3775 } else if messages_delivered == 3 {
3776 // nodes[0] still wants its RAA + commitment_signed
3777 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3778 } else if messages_delivered == 4 {
3779 // nodes[0] still wants its commitment_signed
3780 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3781 } else if messages_delivered == 5 {
3782 // nodes[1] still wants its final RAA
3783 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3784 } else if messages_delivered == 6 {
3785 // Everything was delivered...
3786 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3789 let events_1 = nodes[1].node.get_and_clear_pending_events();
3790 if messages_delivered == 0 {
3791 assert_eq!(events_1.len(), 2);
3793 Event::ChannelReady { .. } => { },
3794 _ => panic!("Unexpected event"),
3797 Event::PendingHTLCsForwardable { .. } => { },
3798 _ => panic!("Unexpected event"),
3801 assert_eq!(events_1.len(), 1);
3803 Event::PendingHTLCsForwardable { .. } => { },
3804 _ => panic!("Unexpected event"),
3808 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3809 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3812 nodes[1].node.process_pending_htlc_forwards();
3814 let events_2 = nodes[1].node.get_and_clear_pending_events();
3815 assert_eq!(events_2.len(), 1);
3817 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3818 assert_eq!(payment_hash_1, *payment_hash);
3819 assert_eq!(amount_msat, 1_000_000);
3820 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3821 assert_eq!(via_channel_id, Some(channel_id));
3823 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3824 assert!(payment_preimage.is_none());
3825 assert_eq!(payment_secret_1, *payment_secret);
3827 _ => panic!("expected PaymentPurpose::InvoicePayment")
3830 _ => panic!("Unexpected event"),
3833 nodes[1].node.claim_funds(payment_preimage_1);
3834 check_added_monitors!(nodes[1], 1);
3835 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3837 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3838 assert_eq!(events_3.len(), 1);
3839 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3840 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3841 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3842 assert!(updates.update_add_htlcs.is_empty());
3843 assert!(updates.update_fail_htlcs.is_empty());
3844 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3845 assert!(updates.update_fail_malformed_htlcs.is_empty());
3846 assert!(updates.update_fee.is_none());
3847 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3849 _ => panic!("Unexpected event"),
3852 if messages_delivered >= 1 {
3853 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3855 let events_4 = nodes[0].node.get_and_clear_pending_events();
3856 assert_eq!(events_4.len(), 1);
3858 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3859 assert_eq!(payment_preimage_1, *payment_preimage);
3860 assert_eq!(payment_hash_1, *payment_hash);
3862 _ => panic!("Unexpected event"),
3865 if messages_delivered >= 2 {
3866 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3867 check_added_monitors!(nodes[0], 1);
3868 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3870 if messages_delivered >= 3 {
3871 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3872 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3873 check_added_monitors!(nodes[1], 1);
3875 if messages_delivered >= 4 {
3876 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3877 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3878 // No commitment_signed so get_event_msg's assert(len == 1) passes
3879 check_added_monitors!(nodes[1], 1);
3881 if messages_delivered >= 5 {
3882 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3883 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3884 check_added_monitors!(nodes[0], 1);
3891 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3892 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3893 if messages_delivered < 2 {
3894 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3895 if messages_delivered < 1 {
3896 expect_payment_sent!(nodes[0], payment_preimage_1);
3898 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3900 } else if messages_delivered == 2 {
3901 // nodes[0] still wants its RAA + commitment_signed
3902 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3903 } else if messages_delivered == 3 {
3904 // nodes[0] still wants its commitment_signed
3905 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3906 } else if messages_delivered == 4 {
3907 // nodes[1] still wants its final RAA
3908 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3909 } else if messages_delivered == 5 {
3910 // Everything was delivered...
3911 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3914 if messages_delivered == 1 || messages_delivered == 2 {
3915 expect_payment_path_successful!(nodes[0]);
3917 if messages_delivered <= 5 {
3918 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3919 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3921 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3923 if messages_delivered > 2 {
3924 expect_payment_path_successful!(nodes[0]);
3927 // Channel should still work fine...
3928 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3929 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3930 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3934 fn test_drop_messages_peer_disconnect_a() {
3935 do_test_drop_messages_peer_disconnect(0, true);
3936 do_test_drop_messages_peer_disconnect(0, false);
3937 do_test_drop_messages_peer_disconnect(1, false);
3938 do_test_drop_messages_peer_disconnect(2, false);
3942 fn test_drop_messages_peer_disconnect_b() {
3943 do_test_drop_messages_peer_disconnect(3, false);
3944 do_test_drop_messages_peer_disconnect(4, false);
3945 do_test_drop_messages_peer_disconnect(5, false);
3946 do_test_drop_messages_peer_disconnect(6, false);
3950 fn test_channel_ready_without_best_block_updated() {
3951 // Previously, if we were offline when a funding transaction was locked in, and then we came
3952 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3953 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3954 // channel_ready immediately instead.
3955 let chanmon_cfgs = create_chanmon_cfgs(2);
3956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3958 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3959 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3961 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3963 let conf_height = nodes[0].best_block_info().1 + 1;
3964 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3965 let block_txn = [funding_tx];
3966 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3967 let conf_block_header = nodes[0].get_block_header(conf_height);
3968 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3970 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3971 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3972 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3976 fn test_drop_messages_peer_disconnect_dual_htlc() {
3977 // Test that we can handle reconnecting when both sides of a channel have pending
3978 // commitment_updates when we disconnect.
3979 let chanmon_cfgs = create_chanmon_cfgs(2);
3980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3982 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3983 create_announced_chan_between_nodes(&nodes, 0, 1);
3985 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3987 // Now try to send a second payment which will fail to send
3988 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3989 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3990 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3991 check_added_monitors!(nodes[0], 1);
3993 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3994 assert_eq!(events_1.len(), 1);
3996 MessageSendEvent::UpdateHTLCs { .. } => {},
3997 _ => panic!("Unexpected event"),
4000 nodes[1].node.claim_funds(payment_preimage_1);
4001 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4002 check_added_monitors!(nodes[1], 1);
4004 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4005 assert_eq!(events_2.len(), 1);
4007 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 } } => {
4008 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4009 assert!(update_add_htlcs.is_empty());
4010 assert_eq!(update_fulfill_htlcs.len(), 1);
4011 assert!(update_fail_htlcs.is_empty());
4012 assert!(update_fail_malformed_htlcs.is_empty());
4013 assert!(update_fee.is_none());
4015 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4016 let events_3 = nodes[0].node.get_and_clear_pending_events();
4017 assert_eq!(events_3.len(), 1);
4019 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4020 assert_eq!(*payment_preimage, payment_preimage_1);
4021 assert_eq!(*payment_hash, payment_hash_1);
4023 _ => panic!("Unexpected event"),
4026 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4027 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4028 // No commitment_signed so get_event_msg's assert(len == 1) passes
4029 check_added_monitors!(nodes[0], 1);
4031 _ => panic!("Unexpected event"),
4034 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4035 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4037 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
4038 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4039 assert_eq!(reestablish_1.len(), 1);
4040 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
4041 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4042 assert_eq!(reestablish_2.len(), 1);
4044 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4045 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4046 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4047 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4049 assert!(as_resp.0.is_none());
4050 assert!(bs_resp.0.is_none());
4052 assert!(bs_resp.1.is_none());
4053 assert!(bs_resp.2.is_none());
4055 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4057 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4058 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4059 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4060 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4061 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4062 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4063 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4064 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4065 // No commitment_signed so get_event_msg's assert(len == 1) passes
4066 check_added_monitors!(nodes[1], 1);
4068 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4069 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4070 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4071 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4072 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4073 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4074 assert!(bs_second_commitment_signed.update_fee.is_none());
4075 check_added_monitors!(nodes[1], 1);
4077 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4078 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4079 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4080 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4081 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4082 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4083 assert!(as_commitment_signed.update_fee.is_none());
4084 check_added_monitors!(nodes[0], 1);
4086 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4087 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4088 // No commitment_signed so get_event_msg's assert(len == 1) passes
4089 check_added_monitors!(nodes[0], 1);
4091 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4092 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4093 // No commitment_signed so get_event_msg's assert(len == 1) passes
4094 check_added_monitors!(nodes[1], 1);
4096 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4097 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4098 check_added_monitors!(nodes[1], 1);
4100 expect_pending_htlcs_forwardable!(nodes[1]);
4102 let events_5 = nodes[1].node.get_and_clear_pending_events();
4103 assert_eq!(events_5.len(), 1);
4105 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4106 assert_eq!(payment_hash_2, *payment_hash);
4108 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4109 assert!(payment_preimage.is_none());
4110 assert_eq!(payment_secret_2, *payment_secret);
4112 _ => panic!("expected PaymentPurpose::InvoicePayment")
4115 _ => panic!("Unexpected event"),
4118 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4119 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4120 check_added_monitors!(nodes[0], 1);
4122 expect_payment_path_successful!(nodes[0]);
4123 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4126 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4127 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4128 // to avoid our counterparty failing the channel.
4129 let chanmon_cfgs = create_chanmon_cfgs(2);
4130 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4132 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4134 create_announced_chan_between_nodes(&nodes, 0, 1);
4136 let our_payment_hash = if send_partial_mpp {
4137 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4138 // Use the utility function send_payment_along_path to send the payment with MPP data which
4139 // indicates there are more HTLCs coming.
4140 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.
4141 let payment_id = PaymentId([42; 32]);
4142 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4143 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4144 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4145 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4146 &None, session_privs[0]).unwrap();
4147 check_added_monitors!(nodes[0], 1);
4148 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4149 assert_eq!(events.len(), 1);
4150 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4151 // hop should *not* yet generate any PaymentClaimable event(s).
4152 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4155 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4158 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4159 connect_block(&nodes[0], &block);
4160 connect_block(&nodes[1], &block);
4161 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4162 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4163 block.header.prev_blockhash = block.block_hash();
4164 connect_block(&nodes[0], &block);
4165 connect_block(&nodes[1], &block);
4168 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4170 check_added_monitors!(nodes[1], 1);
4171 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4172 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4173 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4174 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4175 assert!(htlc_timeout_updates.update_fee.is_none());
4177 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4178 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4179 // 100_000 msat as u64, followed by the height at which we failed back above
4180 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4181 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4182 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4186 fn test_htlc_timeout() {
4187 do_test_htlc_timeout(true);
4188 do_test_htlc_timeout(false);
4191 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4192 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4193 let chanmon_cfgs = create_chanmon_cfgs(3);
4194 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4195 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4196 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4197 create_announced_chan_between_nodes(&nodes, 0, 1);
4198 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4200 // Make sure all nodes are at the same starting height
4201 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4202 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4203 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4205 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4206 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4207 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4208 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4209 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4210 check_added_monitors!(nodes[1], 1);
4212 // Now attempt to route a second payment, which should be placed in the holding cell
4213 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4214 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4215 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4216 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4218 check_added_monitors!(nodes[0], 1);
4219 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4220 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4221 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4222 expect_pending_htlcs_forwardable!(nodes[1]);
4224 check_added_monitors!(nodes[1], 0);
4226 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4227 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4228 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4229 connect_blocks(&nodes[1], 1);
4232 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 }]);
4233 check_added_monitors!(nodes[1], 1);
4234 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4235 assert_eq!(fail_commit.len(), 1);
4236 match fail_commit[0] {
4237 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4238 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4239 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4241 _ => unreachable!(),
4243 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4245 expect_payment_failed!(nodes[1], second_payment_hash, false);
4250 fn test_holding_cell_htlc_add_timeouts() {
4251 do_test_holding_cell_htlc_add_timeouts(false);
4252 do_test_holding_cell_htlc_add_timeouts(true);
4255 macro_rules! check_spendable_outputs {
4256 ($node: expr, $keysinterface: expr) => {
4258 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4259 let mut txn = Vec::new();
4260 let mut all_outputs = Vec::new();
4261 let secp_ctx = Secp256k1::new();
4262 for event in events.drain(..) {
4264 Event::SpendableOutputs { mut outputs } => {
4265 for outp in outputs.drain(..) {
4266 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());
4267 all_outputs.push(outp);
4270 _ => panic!("Unexpected event"),
4273 if all_outputs.len() > 1 {
4274 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) {
4284 fn test_claim_sizeable_push_msat() {
4285 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4286 let chanmon_cfgs = create_chanmon_cfgs(2);
4287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4289 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4291 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4292 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4293 check_closed_broadcast!(nodes[1], true);
4294 check_added_monitors!(nodes[1], 1);
4295 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4296 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4297 assert_eq!(node_txn.len(), 1);
4298 check_spends!(node_txn[0], chan.3);
4299 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
4301 mine_transaction(&nodes[1], &node_txn[0]);
4302 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4304 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4305 assert_eq!(spend_txn.len(), 1);
4306 assert_eq!(spend_txn[0].input.len(), 1);
4307 check_spends!(spend_txn[0], node_txn[0]);
4308 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4312 fn test_claim_on_remote_sizeable_push_msat() {
4313 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4314 // to_remote output is encumbered by a P2WPKH
4315 let chanmon_cfgs = create_chanmon_cfgs(2);
4316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4318 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4320 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4321 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4322 check_closed_broadcast!(nodes[0], true);
4323 check_added_monitors!(nodes[0], 1);
4324 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4326 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4327 assert_eq!(node_txn.len(), 1);
4328 check_spends!(node_txn[0], chan.3);
4329 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
4331 mine_transaction(&nodes[1], &node_txn[0]);
4332 check_closed_broadcast!(nodes[1], true);
4333 check_added_monitors!(nodes[1], 1);
4334 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4335 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4337 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4338 assert_eq!(spend_txn.len(), 1);
4339 check_spends!(spend_txn[0], node_txn[0]);
4343 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4344 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4345 // to_remote output is encumbered by a P2WPKH
4347 let chanmon_cfgs = create_chanmon_cfgs(2);
4348 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4349 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4350 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4352 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4353 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4354 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4355 assert_eq!(revoked_local_txn[0].input.len(), 1);
4356 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4358 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4359 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4360 check_closed_broadcast!(nodes[1], true);
4361 check_added_monitors!(nodes[1], 1);
4362 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4364 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4365 mine_transaction(&nodes[1], &node_txn[0]);
4366 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4368 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4369 assert_eq!(spend_txn.len(), 3);
4370 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4371 check_spends!(spend_txn[1], node_txn[0]);
4372 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4376 fn test_static_spendable_outputs_preimage_tx() {
4377 let chanmon_cfgs = create_chanmon_cfgs(2);
4378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4380 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4382 // Create some initial channels
4383 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4385 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4387 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4388 assert_eq!(commitment_tx[0].input.len(), 1);
4389 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4391 // Settle A's commitment tx on B's chain
4392 nodes[1].node.claim_funds(payment_preimage);
4393 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4394 check_added_monitors!(nodes[1], 1);
4395 mine_transaction(&nodes[1], &commitment_tx[0]);
4396 check_added_monitors!(nodes[1], 1);
4397 let events = nodes[1].node.get_and_clear_pending_msg_events();
4399 MessageSendEvent::UpdateHTLCs { .. } => {},
4400 _ => panic!("Unexpected event"),
4403 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4404 _ => panic!("Unexepected event"),
4407 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4408 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4409 assert_eq!(node_txn.len(), 1);
4410 check_spends!(node_txn[0], commitment_tx[0]);
4411 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4413 mine_transaction(&nodes[1], &node_txn[0]);
4414 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4415 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4417 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4418 assert_eq!(spend_txn.len(), 1);
4419 check_spends!(spend_txn[0], node_txn[0]);
4423 fn test_static_spendable_outputs_timeout_tx() {
4424 let chanmon_cfgs = create_chanmon_cfgs(2);
4425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4427 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4429 // Create some initial channels
4430 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4432 // Rebalance the network a bit by relaying one payment through all the channels ...
4433 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4435 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4437 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4438 assert_eq!(commitment_tx[0].input.len(), 1);
4439 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4441 // Settle A's commitment tx on B' chain
4442 mine_transaction(&nodes[1], &commitment_tx[0]);
4443 check_added_monitors!(nodes[1], 1);
4444 let events = nodes[1].node.get_and_clear_pending_msg_events();
4446 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4447 _ => panic!("Unexpected event"),
4449 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4451 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4452 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4453 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4454 check_spends!(node_txn[0], commitment_tx[0].clone());
4455 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4457 mine_transaction(&nodes[1], &node_txn[0]);
4458 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4459 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4460 expect_payment_failed!(nodes[1], our_payment_hash, false);
4462 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4463 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4464 check_spends!(spend_txn[0], commitment_tx[0]);
4465 check_spends!(spend_txn[1], node_txn[0]);
4466 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4470 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4471 let chanmon_cfgs = create_chanmon_cfgs(2);
4472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4476 // Create some initial channels
4477 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4479 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4480 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4481 assert_eq!(revoked_local_txn[0].input.len(), 1);
4482 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4484 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4486 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4487 check_closed_broadcast!(nodes[1], true);
4488 check_added_monitors!(nodes[1], 1);
4489 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4491 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4492 assert_eq!(node_txn.len(), 1);
4493 assert_eq!(node_txn[0].input.len(), 2);
4494 check_spends!(node_txn[0], revoked_local_txn[0]);
4496 mine_transaction(&nodes[1], &node_txn[0]);
4497 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4499 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4500 assert_eq!(spend_txn.len(), 1);
4501 check_spends!(spend_txn[0], node_txn[0]);
4505 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4506 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4507 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4508 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4509 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4510 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4512 // Create some initial channels
4513 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4515 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4516 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4517 assert_eq!(revoked_local_txn[0].input.len(), 1);
4518 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4520 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4522 // A will generate HTLC-Timeout from revoked commitment tx
4523 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4524 check_closed_broadcast!(nodes[0], true);
4525 check_added_monitors!(nodes[0], 1);
4526 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4527 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4529 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4530 assert_eq!(revoked_htlc_txn.len(), 1);
4531 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4532 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4533 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4534 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4536 // B will generate justice tx from A's revoked commitment/HTLC tx
4537 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4538 check_closed_broadcast!(nodes[1], true);
4539 check_added_monitors!(nodes[1], 1);
4540 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4542 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4543 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4544 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4545 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4546 // transactions next...
4547 assert_eq!(node_txn[0].input.len(), 3);
4548 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4550 assert_eq!(node_txn[1].input.len(), 2);
4551 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4552 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4553 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4555 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4556 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4559 mine_transaction(&nodes[1], &node_txn[1]);
4560 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4562 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4563 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4564 assert_eq!(spend_txn.len(), 1);
4565 assert_eq!(spend_txn[0].input.len(), 1);
4566 check_spends!(spend_txn[0], node_txn[1]);
4570 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4571 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4572 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4575 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4577 // Create some initial channels
4578 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4580 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4581 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4582 assert_eq!(revoked_local_txn[0].input.len(), 1);
4583 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4585 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4586 assert_eq!(revoked_local_txn[0].output.len(), 2);
4588 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4590 // B will generate HTLC-Success from revoked commitment tx
4591 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4592 check_closed_broadcast!(nodes[1], true);
4593 check_added_monitors!(nodes[1], 1);
4594 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4595 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4597 assert_eq!(revoked_htlc_txn.len(), 1);
4598 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4599 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4600 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4602 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4603 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4604 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4606 // A will generate justice tx from B's revoked commitment/HTLC tx
4607 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4608 check_closed_broadcast!(nodes[0], true);
4609 check_added_monitors!(nodes[0], 1);
4610 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4612 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4613 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4615 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4616 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4617 // transactions next...
4618 assert_eq!(node_txn[0].input.len(), 2);
4619 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4620 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4621 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4623 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4624 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4627 assert_eq!(node_txn[1].input.len(), 1);
4628 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4630 mine_transaction(&nodes[0], &node_txn[1]);
4631 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4633 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4634 // didn't try to generate any new transactions.
4636 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4637 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4638 assert_eq!(spend_txn.len(), 3);
4639 assert_eq!(spend_txn[0].input.len(), 1);
4640 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4641 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4642 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4643 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4647 fn test_onchain_to_onchain_claim() {
4648 // Test that in case of channel closure, we detect the state of output and claim HTLC
4649 // on downstream peer's remote commitment tx.
4650 // First, have C claim an HTLC against its own latest commitment transaction.
4651 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4653 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4656 let chanmon_cfgs = create_chanmon_cfgs(3);
4657 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4658 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4659 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4661 // Create some initial channels
4662 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4663 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4665 // Ensure all nodes are at the same height
4666 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4667 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4668 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4669 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4671 // Rebalance the network a bit by relaying one payment through all the channels ...
4672 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4673 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4675 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4676 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4677 check_spends!(commitment_tx[0], chan_2.3);
4678 nodes[2].node.claim_funds(payment_preimage);
4679 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4680 check_added_monitors!(nodes[2], 1);
4681 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4682 assert!(updates.update_add_htlcs.is_empty());
4683 assert!(updates.update_fail_htlcs.is_empty());
4684 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4685 assert!(updates.update_fail_malformed_htlcs.is_empty());
4687 mine_transaction(&nodes[2], &commitment_tx[0]);
4688 check_closed_broadcast!(nodes[2], true);
4689 check_added_monitors!(nodes[2], 1);
4690 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4692 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4693 assert_eq!(c_txn.len(), 1);
4694 check_spends!(c_txn[0], commitment_tx[0]);
4695 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4696 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4697 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4699 // 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
4700 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4701 check_added_monitors!(nodes[1], 1);
4702 let events = nodes[1].node.get_and_clear_pending_events();
4703 assert_eq!(events.len(), 2);
4705 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4706 _ => panic!("Unexpected event"),
4709 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4710 assert_eq!(fee_earned_msat, Some(1000));
4711 assert_eq!(prev_channel_id, Some(chan_1.2));
4712 assert_eq!(claim_from_onchain_tx, true);
4713 assert_eq!(next_channel_id, Some(chan_2.2));
4714 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4716 _ => panic!("Unexpected event"),
4718 check_added_monitors!(nodes[1], 1);
4719 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4720 assert_eq!(msg_events.len(), 3);
4721 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4722 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4724 match nodes_2_event {
4725 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4726 _ => panic!("Unexpected event"),
4729 match nodes_0_event {
4730 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, .. } } => {
4731 assert!(update_add_htlcs.is_empty());
4732 assert!(update_fail_htlcs.is_empty());
4733 assert_eq!(update_fulfill_htlcs.len(), 1);
4734 assert!(update_fail_malformed_htlcs.is_empty());
4735 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4737 _ => panic!("Unexpected event"),
4740 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4741 match msg_events[0] {
4742 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4743 _ => panic!("Unexpected event"),
4746 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4747 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4748 mine_transaction(&nodes[1], &commitment_tx[0]);
4749 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4750 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4751 // ChannelMonitor: HTLC-Success tx
4752 assert_eq!(b_txn.len(), 1);
4753 check_spends!(b_txn[0], commitment_tx[0]);
4754 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4755 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4756 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4758 check_closed_broadcast!(nodes[1], true);
4759 check_added_monitors!(nodes[1], 1);
4763 fn test_duplicate_payment_hash_one_failure_one_success() {
4764 // Topology : A --> B --> C --> D
4765 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4766 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4767 // we forward one of the payments onwards to D.
4768 let chanmon_cfgs = create_chanmon_cfgs(4);
4769 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4770 // When this test was written, the default base fee floated based on the HTLC count.
4771 // It is now fixed, so we simply set the fee to the expected value here.
4772 let mut config = test_default_channel_config();
4773 config.channel_config.forwarding_fee_base_msat = 196;
4774 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4775 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4776 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4778 create_announced_chan_between_nodes(&nodes, 0, 1);
4779 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4780 create_announced_chan_between_nodes(&nodes, 2, 3);
4782 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4783 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4784 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4785 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4786 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4788 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4790 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4791 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4792 // script push size limit so that the below script length checks match
4793 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4794 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4795 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4796 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4797 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4799 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4800 assert_eq!(commitment_txn[0].input.len(), 1);
4801 check_spends!(commitment_txn[0], chan_2.3);
4803 mine_transaction(&nodes[1], &commitment_txn[0]);
4804 check_closed_broadcast!(nodes[1], true);
4805 check_added_monitors!(nodes[1], 1);
4806 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4807 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4809 let htlc_timeout_tx;
4810 { // Extract one of the two HTLC-Timeout transaction
4811 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4812 // ChannelMonitor: timeout tx * 2-or-3
4813 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4815 check_spends!(node_txn[0], commitment_txn[0]);
4816 assert_eq!(node_txn[0].input.len(), 1);
4817 assert_eq!(node_txn[0].output.len(), 1);
4819 if node_txn.len() > 2 {
4820 check_spends!(node_txn[1], commitment_txn[0]);
4821 assert_eq!(node_txn[1].input.len(), 1);
4822 assert_eq!(node_txn[1].output.len(), 1);
4823 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4825 check_spends!(node_txn[2], commitment_txn[0]);
4826 assert_eq!(node_txn[2].input.len(), 1);
4827 assert_eq!(node_txn[2].output.len(), 1);
4828 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4830 check_spends!(node_txn[1], commitment_txn[0]);
4831 assert_eq!(node_txn[1].input.len(), 1);
4832 assert_eq!(node_txn[1].output.len(), 1);
4833 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4836 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4837 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4838 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4839 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4840 if node_txn.len() > 2 {
4841 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4842 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4844 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4848 nodes[2].node.claim_funds(our_payment_preimage);
4849 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4851 mine_transaction(&nodes[2], &commitment_txn[0]);
4852 check_added_monitors!(nodes[2], 2);
4853 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4854 let events = nodes[2].node.get_and_clear_pending_msg_events();
4856 MessageSendEvent::UpdateHTLCs { .. } => {},
4857 _ => panic!("Unexpected event"),
4860 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4861 _ => panic!("Unexepected event"),
4863 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4864 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4865 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4866 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4867 assert_eq!(htlc_success_txn[0].input.len(), 1);
4868 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4869 assert_eq!(htlc_success_txn[1].input.len(), 1);
4870 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4871 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4872 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4874 mine_transaction(&nodes[1], &htlc_timeout_tx);
4875 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4876 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 }]);
4877 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4878 assert!(htlc_updates.update_add_htlcs.is_empty());
4879 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4880 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4881 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4882 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4883 check_added_monitors!(nodes[1], 1);
4885 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4888 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4890 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4892 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4893 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4894 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4895 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4896 assert!(updates.update_add_htlcs.is_empty());
4897 assert!(updates.update_fail_htlcs.is_empty());
4898 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4899 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4900 assert!(updates.update_fail_malformed_htlcs.is_empty());
4901 check_added_monitors!(nodes[1], 1);
4903 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4904 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4905 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4909 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4910 let chanmon_cfgs = create_chanmon_cfgs(2);
4911 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4912 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4913 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4915 // Create some initial channels
4916 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4918 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4919 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4920 assert_eq!(local_txn.len(), 1);
4921 assert_eq!(local_txn[0].input.len(), 1);
4922 check_spends!(local_txn[0], chan_1.3);
4924 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4925 nodes[1].node.claim_funds(payment_preimage);
4926 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4927 check_added_monitors!(nodes[1], 1);
4929 mine_transaction(&nodes[1], &local_txn[0]);
4930 check_added_monitors!(nodes[1], 1);
4931 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4932 let events = nodes[1].node.get_and_clear_pending_msg_events();
4934 MessageSendEvent::UpdateHTLCs { .. } => {},
4935 _ => panic!("Unexpected event"),
4938 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4939 _ => panic!("Unexepected event"),
4942 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4943 assert_eq!(node_txn.len(), 1);
4944 assert_eq!(node_txn[0].input.len(), 1);
4945 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4946 check_spends!(node_txn[0], local_txn[0]);
4950 mine_transaction(&nodes[1], &node_tx);
4951 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4953 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4954 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4955 assert_eq!(spend_txn.len(), 1);
4956 assert_eq!(spend_txn[0].input.len(), 1);
4957 check_spends!(spend_txn[0], node_tx);
4958 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4961 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4962 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4963 // unrevoked commitment transaction.
4964 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4965 // a remote RAA before they could be failed backwards (and combinations thereof).
4966 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4967 // use the same payment hashes.
4968 // Thus, we use a six-node network:
4973 // And test where C fails back to A/B when D announces its latest commitment transaction
4974 let chanmon_cfgs = create_chanmon_cfgs(6);
4975 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4976 // When this test was written, the default base fee floated based on the HTLC count.
4977 // It is now fixed, so we simply set the fee to the expected value here.
4978 let mut config = test_default_channel_config();
4979 config.channel_config.forwarding_fee_base_msat = 196;
4980 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4981 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4982 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4984 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4985 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4986 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4987 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4988 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4990 // Rebalance and check output sanity...
4991 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4992 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4993 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4995 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4996 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4998 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
5000 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
5001 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5003 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
5005 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
5007 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5009 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5010 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5012 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());
5014 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());
5017 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5019 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5020 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
5023 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
5025 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5026 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());
5028 // Double-check that six of the new HTLC were added
5029 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5030 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5031 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5032 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5034 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5035 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5036 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5037 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5038 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5039 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5040 check_added_monitors!(nodes[4], 0);
5042 let failed_destinations = vec![
5043 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5044 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5045 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5046 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5048 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5049 check_added_monitors!(nodes[4], 1);
5051 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5052 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5053 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5054 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5055 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5056 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5058 // Fail 3rd below-dust and 7th above-dust HTLCs
5059 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5060 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5061 check_added_monitors!(nodes[5], 0);
5063 let failed_destinations_2 = vec![
5064 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5065 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5067 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5068 check_added_monitors!(nodes[5], 1);
5070 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5071 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5072 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5073 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5075 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5077 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5078 let failed_destinations_3 = vec![
5079 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5080 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5081 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5082 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5083 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5084 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5086 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5087 check_added_monitors!(nodes[3], 1);
5088 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5089 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5090 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5091 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5092 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5093 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5094 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5095 if deliver_last_raa {
5096 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5098 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5101 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5102 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5103 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5104 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5106 // We now broadcast the latest commitment transaction, which *should* result in failures for
5107 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5108 // the non-broadcast above-dust HTLCs.
5110 // Alternatively, we may broadcast the previous commitment transaction, which should only
5111 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5112 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5114 if announce_latest {
5115 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5117 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5119 let events = nodes[2].node.get_and_clear_pending_events();
5120 let close_event = if deliver_last_raa {
5121 assert_eq!(events.len(), 2 + 6);
5122 events.last().clone().unwrap()
5124 assert_eq!(events.len(), 1);
5125 events.last().clone().unwrap()
5128 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5129 _ => panic!("Unexpected event"),
5132 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5133 check_closed_broadcast!(nodes[2], true);
5134 if deliver_last_raa {
5135 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5137 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();
5138 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5140 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5141 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5143 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5146 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5148 check_added_monitors!(nodes[2], 3);
5150 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5151 assert_eq!(cs_msgs.len(), 2);
5152 let mut a_done = false;
5153 for msg in cs_msgs {
5155 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5156 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5157 // should be failed-backwards here.
5158 let target = if *node_id == nodes[0].node.get_our_node_id() {
5159 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5160 for htlc in &updates.update_fail_htlcs {
5161 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 });
5163 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5168 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5169 for htlc in &updates.update_fail_htlcs {
5170 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5172 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5173 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5176 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5177 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5178 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5179 if announce_latest {
5180 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5181 if *node_id == nodes[0].node.get_our_node_id() {
5182 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5185 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5187 _ => panic!("Unexpected event"),
5191 let as_events = nodes[0].node.get_and_clear_pending_events();
5192 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5193 let mut as_failds = HashSet::new();
5194 let mut as_updates = 0;
5195 for event in as_events.iter() {
5196 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5197 assert!(as_failds.insert(*payment_hash));
5198 if *payment_hash != payment_hash_2 {
5199 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5201 assert!(!payment_failed_permanently);
5203 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5206 } else if let &Event::PaymentFailed { .. } = event {
5207 } else { panic!("Unexpected event"); }
5209 assert!(as_failds.contains(&payment_hash_1));
5210 assert!(as_failds.contains(&payment_hash_2));
5211 if announce_latest {
5212 assert!(as_failds.contains(&payment_hash_3));
5213 assert!(as_failds.contains(&payment_hash_5));
5215 assert!(as_failds.contains(&payment_hash_6));
5217 let bs_events = nodes[1].node.get_and_clear_pending_events();
5218 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5219 let mut bs_failds = HashSet::new();
5220 let mut bs_updates = 0;
5221 for event in bs_events.iter() {
5222 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5223 assert!(bs_failds.insert(*payment_hash));
5224 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5225 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5227 assert!(!payment_failed_permanently);
5229 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5232 } else if let &Event::PaymentFailed { .. } = event {
5233 } else { panic!("Unexpected event"); }
5235 assert!(bs_failds.contains(&payment_hash_1));
5236 assert!(bs_failds.contains(&payment_hash_2));
5237 if announce_latest {
5238 assert!(bs_failds.contains(&payment_hash_4));
5240 assert!(bs_failds.contains(&payment_hash_5));
5242 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5243 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5244 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5245 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5246 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5247 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5251 fn test_fail_backwards_latest_remote_announce_a() {
5252 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5256 fn test_fail_backwards_latest_remote_announce_b() {
5257 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5261 fn test_fail_backwards_previous_remote_announce() {
5262 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5263 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5264 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5268 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5269 let chanmon_cfgs = create_chanmon_cfgs(2);
5270 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5271 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5272 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5274 // Create some initial channels
5275 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5277 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5278 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5279 assert_eq!(local_txn[0].input.len(), 1);
5280 check_spends!(local_txn[0], chan_1.3);
5282 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5283 mine_transaction(&nodes[0], &local_txn[0]);
5284 check_closed_broadcast!(nodes[0], true);
5285 check_added_monitors!(nodes[0], 1);
5286 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5287 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5289 let htlc_timeout = {
5290 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5291 assert_eq!(node_txn.len(), 1);
5292 assert_eq!(node_txn[0].input.len(), 1);
5293 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5294 check_spends!(node_txn[0], local_txn[0]);
5298 mine_transaction(&nodes[0], &htlc_timeout);
5299 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5300 expect_payment_failed!(nodes[0], our_payment_hash, false);
5302 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5303 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5304 assert_eq!(spend_txn.len(), 3);
5305 check_spends!(spend_txn[0], local_txn[0]);
5306 assert_eq!(spend_txn[1].input.len(), 1);
5307 check_spends!(spend_txn[1], htlc_timeout);
5308 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5309 assert_eq!(spend_txn[2].input.len(), 2);
5310 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5311 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5312 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5316 fn test_key_derivation_params() {
5317 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5318 // manager rotation to test that `channel_keys_id` returned in
5319 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5320 // then derive a `delayed_payment_key`.
5322 let chanmon_cfgs = create_chanmon_cfgs(3);
5324 // We manually create the node configuration to backup the seed.
5325 let seed = [42; 32];
5326 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5327 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);
5328 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5329 let scorer = Mutex::new(test_utils::TestScorer::new());
5330 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5331 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)) };
5332 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5333 node_cfgs.remove(0);
5334 node_cfgs.insert(0, node);
5336 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5337 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5339 // Create some initial channels
5340 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5342 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5343 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5344 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5346 // Ensure all nodes are at the same height
5347 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5348 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5349 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5350 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5352 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5353 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5354 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5355 assert_eq!(local_txn_1[0].input.len(), 1);
5356 check_spends!(local_txn_1[0], chan_1.3);
5358 // We check funding pubkey are unique
5359 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]));
5360 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]));
5361 if from_0_funding_key_0 == from_1_funding_key_0
5362 || from_0_funding_key_0 == from_1_funding_key_1
5363 || from_0_funding_key_1 == from_1_funding_key_0
5364 || from_0_funding_key_1 == from_1_funding_key_1 {
5365 panic!("Funding pubkeys aren't unique");
5368 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5369 mine_transaction(&nodes[0], &local_txn_1[0]);
5370 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5371 check_closed_broadcast!(nodes[0], true);
5372 check_added_monitors!(nodes[0], 1);
5373 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5375 let htlc_timeout = {
5376 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5377 assert_eq!(node_txn.len(), 1);
5378 assert_eq!(node_txn[0].input.len(), 1);
5379 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5380 check_spends!(node_txn[0], local_txn_1[0]);
5384 mine_transaction(&nodes[0], &htlc_timeout);
5385 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5386 expect_payment_failed!(nodes[0], our_payment_hash, false);
5388 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5389 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5390 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5391 assert_eq!(spend_txn.len(), 3);
5392 check_spends!(spend_txn[0], local_txn_1[0]);
5393 assert_eq!(spend_txn[1].input.len(), 1);
5394 check_spends!(spend_txn[1], htlc_timeout);
5395 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5396 assert_eq!(spend_txn[2].input.len(), 2);
5397 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5398 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5399 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5403 fn test_static_output_closing_tx() {
5404 let chanmon_cfgs = create_chanmon_cfgs(2);
5405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5407 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5409 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5411 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5412 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5414 mine_transaction(&nodes[0], &closing_tx);
5415 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5416 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5418 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5419 assert_eq!(spend_txn.len(), 1);
5420 check_spends!(spend_txn[0], closing_tx);
5422 mine_transaction(&nodes[1], &closing_tx);
5423 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5424 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5426 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5427 assert_eq!(spend_txn.len(), 1);
5428 check_spends!(spend_txn[0], closing_tx);
5431 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5432 let chanmon_cfgs = create_chanmon_cfgs(2);
5433 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5434 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5435 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5436 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5438 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5440 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5441 // present in B's local commitment transaction, but none of A's commitment transactions.
5442 nodes[1].node.claim_funds(payment_preimage);
5443 check_added_monitors!(nodes[1], 1);
5444 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5446 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5447 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5448 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5450 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5451 check_added_monitors!(nodes[0], 1);
5452 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5453 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5454 check_added_monitors!(nodes[1], 1);
5456 let starting_block = nodes[1].best_block_info();
5457 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5458 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5459 connect_block(&nodes[1], &block);
5460 block.header.prev_blockhash = block.block_hash();
5462 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5463 check_closed_broadcast!(nodes[1], true);
5464 check_added_monitors!(nodes[1], 1);
5465 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5468 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5469 let chanmon_cfgs = create_chanmon_cfgs(2);
5470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5473 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5475 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5476 nodes[0].node.send_payment_with_route(&route, payment_hash,
5477 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5478 check_added_monitors!(nodes[0], 1);
5480 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5482 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5483 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5484 // to "time out" the HTLC.
5486 let starting_block = nodes[1].best_block_info();
5487 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5489 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5490 connect_block(&nodes[0], &block);
5491 block.header.prev_blockhash = block.block_hash();
5493 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5494 check_closed_broadcast!(nodes[0], true);
5495 check_added_monitors!(nodes[0], 1);
5496 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5499 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5500 let chanmon_cfgs = create_chanmon_cfgs(3);
5501 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5502 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5503 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5504 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5506 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5507 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5508 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5509 // actually revoked.
5510 let htlc_value = if use_dust { 50000 } else { 3000000 };
5511 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5512 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5513 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5514 check_added_monitors!(nodes[1], 1);
5516 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5517 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5518 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5519 check_added_monitors!(nodes[0], 1);
5520 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5521 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5522 check_added_monitors!(nodes[1], 1);
5523 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5524 check_added_monitors!(nodes[1], 1);
5525 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5527 if check_revoke_no_close {
5528 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5529 check_added_monitors!(nodes[0], 1);
5532 let starting_block = nodes[1].best_block_info();
5533 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5534 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5535 connect_block(&nodes[0], &block);
5536 block.header.prev_blockhash = block.block_hash();
5538 if !check_revoke_no_close {
5539 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5540 check_closed_broadcast!(nodes[0], true);
5541 check_added_monitors!(nodes[0], 1);
5542 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5544 expect_payment_failed!(nodes[0], our_payment_hash, true);
5548 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5549 // There are only a few cases to test here:
5550 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5551 // broadcastable commitment transactions result in channel closure,
5552 // * its included in an unrevoked-but-previous remote commitment transaction,
5553 // * its included in the latest remote or local commitment transactions.
5554 // We test each of the three possible commitment transactions individually and use both dust and
5556 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5557 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5558 // tested for at least one of the cases in other tests.
5560 fn htlc_claim_single_commitment_only_a() {
5561 do_htlc_claim_local_commitment_only(true);
5562 do_htlc_claim_local_commitment_only(false);
5564 do_htlc_claim_current_remote_commitment_only(true);
5565 do_htlc_claim_current_remote_commitment_only(false);
5569 fn htlc_claim_single_commitment_only_b() {
5570 do_htlc_claim_previous_remote_commitment_only(true, false);
5571 do_htlc_claim_previous_remote_commitment_only(false, false);
5572 do_htlc_claim_previous_remote_commitment_only(true, true);
5573 do_htlc_claim_previous_remote_commitment_only(false, true);
5578 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5579 let chanmon_cfgs = create_chanmon_cfgs(2);
5580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5582 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5583 // Force duplicate randomness for every get-random call
5584 for node in nodes.iter() {
5585 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5588 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5589 let channel_value_satoshis=10000;
5590 let push_msat=10001;
5591 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5592 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5593 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5594 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5596 // Create a second channel with the same random values. This used to panic due to a colliding
5597 // channel_id, but now panics due to a colliding outbound SCID alias.
5598 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5602 fn bolt2_open_channel_sending_node_checks_part2() {
5603 let chanmon_cfgs = create_chanmon_cfgs(2);
5604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5606 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5608 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5609 let channel_value_satoshis=2^24;
5610 let push_msat=10001;
5611 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5613 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5614 let channel_value_satoshis=10000;
5615 // Test when push_msat is equal to 1000 * funding_satoshis.
5616 let push_msat=1000*channel_value_satoshis+1;
5617 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5619 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5620 let channel_value_satoshis=10000;
5621 let push_msat=10001;
5622 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
5623 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5624 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5626 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5627 // 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
5628 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5630 // 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.
5631 assert!(BREAKDOWN_TIMEOUT>0);
5632 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5634 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5635 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5636 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5638 // 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.
5639 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5640 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5641 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5642 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5643 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5647 fn bolt2_open_channel_sane_dust_limit() {
5648 let chanmon_cfgs = create_chanmon_cfgs(2);
5649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5651 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5653 let channel_value_satoshis=1000000;
5654 let push_msat=10001;
5655 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5656 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5657 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5658 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5660 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5661 let events = nodes[1].node.get_and_clear_pending_msg_events();
5662 let err_msg = match events[0] {
5663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5666 _ => panic!("Unexpected event"),
5668 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5671 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5672 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5673 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5674 // is no longer affordable once it's freed.
5676 fn test_fail_holding_cell_htlc_upon_free() {
5677 let chanmon_cfgs = create_chanmon_cfgs(2);
5678 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5679 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5680 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5681 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5683 // First nodes[0] generates an update_fee, setting the channel's
5684 // pending_update_fee.
5686 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5687 *feerate_lock += 20;
5689 nodes[0].node.timer_tick_occurred();
5690 check_added_monitors!(nodes[0], 1);
5692 let events = nodes[0].node.get_and_clear_pending_msg_events();
5693 assert_eq!(events.len(), 1);
5694 let (update_msg, commitment_signed) = match events[0] {
5695 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5696 (update_fee.as_ref(), commitment_signed)
5698 _ => panic!("Unexpected event"),
5701 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5703 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5704 let channel_reserve = chan_stat.channel_reserve_msat;
5705 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5706 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5708 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5709 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5710 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5712 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5713 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5714 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5715 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5716 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5718 // Flush the pending fee update.
5719 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5720 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5721 check_added_monitors!(nodes[1], 1);
5722 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5723 check_added_monitors!(nodes[0], 1);
5725 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5726 // HTLC, but now that the fee has been raised the payment will now fail, causing
5727 // us to surface its failure to the user.
5728 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5729 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5730 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);
5731 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 {}",
5732 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5733 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5735 // Check that the payment failed to be sent out.
5736 let events = nodes[0].node.get_and_clear_pending_events();
5737 assert_eq!(events.len(), 2);
5739 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5740 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5741 assert_eq!(our_payment_hash.clone(), *payment_hash);
5742 assert_eq!(*payment_failed_permanently, false);
5743 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5745 _ => panic!("Unexpected event"),
5748 &Event::PaymentFailed { ref payment_hash, .. } => {
5749 assert_eq!(our_payment_hash.clone(), *payment_hash);
5751 _ => panic!("Unexpected event"),
5755 // Test that if multiple HTLCs are released from the holding cell and one is
5756 // valid but the other is no longer valid upon release, the valid HTLC can be
5757 // successfully completed while the other one fails as expected.
5759 fn test_free_and_fail_holding_cell_htlcs() {
5760 let chanmon_cfgs = create_chanmon_cfgs(2);
5761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5764 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5766 // First nodes[0] generates an update_fee, setting the channel's
5767 // pending_update_fee.
5769 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5770 *feerate_lock += 200;
5772 nodes[0].node.timer_tick_occurred();
5773 check_added_monitors!(nodes[0], 1);
5775 let events = nodes[0].node.get_and_clear_pending_msg_events();
5776 assert_eq!(events.len(), 1);
5777 let (update_msg, commitment_signed) = match events[0] {
5778 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5779 (update_fee.as_ref(), commitment_signed)
5781 _ => panic!("Unexpected event"),
5784 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5786 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5787 let channel_reserve = chan_stat.channel_reserve_msat;
5788 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5789 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5791 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5793 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5794 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5795 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5797 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5798 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5799 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).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);
5802 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5803 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5804 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5805 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5806 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5808 // Flush the pending fee update.
5809 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5810 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5811 check_added_monitors!(nodes[1], 1);
5812 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5813 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5814 check_added_monitors!(nodes[0], 2);
5816 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5817 // but now that the fee has been raised the second payment will now fail, causing us
5818 // to surface its failure to the user. The first payment should succeed.
5819 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5820 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5821 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);
5822 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 {}",
5823 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5824 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5826 // Check that the second payment failed to be sent out.
5827 let events = nodes[0].node.get_and_clear_pending_events();
5828 assert_eq!(events.len(), 2);
5830 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5831 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5832 assert_eq!(payment_hash_2.clone(), *payment_hash);
5833 assert_eq!(*payment_failed_permanently, false);
5834 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5836 _ => panic!("Unexpected event"),
5839 &Event::PaymentFailed { ref payment_hash, .. } => {
5840 assert_eq!(payment_hash_2.clone(), *payment_hash);
5842 _ => panic!("Unexpected event"),
5845 // Complete the first payment and the RAA from the fee update.
5846 let (payment_event, send_raa_event) = {
5847 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5848 assert_eq!(msgs.len(), 2);
5849 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5851 let raa = match send_raa_event {
5852 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5853 _ => panic!("Unexpected event"),
5855 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5856 check_added_monitors!(nodes[1], 1);
5857 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5858 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5859 let events = nodes[1].node.get_and_clear_pending_events();
5860 assert_eq!(events.len(), 1);
5862 Event::PendingHTLCsForwardable { .. } => {},
5863 _ => panic!("Unexpected event"),
5865 nodes[1].node.process_pending_htlc_forwards();
5866 let events = nodes[1].node.get_and_clear_pending_events();
5867 assert_eq!(events.len(), 1);
5869 Event::PaymentClaimable { .. } => {},
5870 _ => panic!("Unexpected event"),
5872 nodes[1].node.claim_funds(payment_preimage_1);
5873 check_added_monitors!(nodes[1], 1);
5874 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5876 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5877 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5878 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5879 expect_payment_sent!(nodes[0], payment_preimage_1);
5882 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5883 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5884 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5887 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5888 let chanmon_cfgs = create_chanmon_cfgs(3);
5889 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5890 // Avoid having to include routing fees in calculations
5891 let mut config = test_default_channel_config();
5892 config.channel_config.forwarding_fee_base_msat = 0;
5893 config.channel_config.forwarding_fee_proportional_millionths = 0;
5894 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5895 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5896 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5897 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5899 // First nodes[1] generates an update_fee, setting the channel's
5900 // pending_update_fee.
5902 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5903 *feerate_lock += 20;
5905 nodes[1].node.timer_tick_occurred();
5906 check_added_monitors!(nodes[1], 1);
5908 let events = nodes[1].node.get_and_clear_pending_msg_events();
5909 assert_eq!(events.len(), 1);
5910 let (update_msg, commitment_signed) = match events[0] {
5911 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5912 (update_fee.as_ref(), commitment_signed)
5914 _ => panic!("Unexpected event"),
5917 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5919 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5920 let channel_reserve = chan_stat.channel_reserve_msat;
5921 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5922 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5924 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5925 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5926 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5927 let payment_event = {
5928 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5929 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5930 check_added_monitors!(nodes[0], 1);
5932 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5933 assert_eq!(events.len(), 1);
5935 SendEvent::from_event(events.remove(0))
5937 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5938 check_added_monitors!(nodes[1], 0);
5939 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5940 expect_pending_htlcs_forwardable!(nodes[1]);
5942 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5943 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5945 // Flush the pending fee update.
5946 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5947 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5948 check_added_monitors!(nodes[2], 1);
5949 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5950 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5951 check_added_monitors!(nodes[1], 2);
5953 // A final RAA message is generated to finalize the fee update.
5954 let events = nodes[1].node.get_and_clear_pending_msg_events();
5955 assert_eq!(events.len(), 1);
5957 let raa_msg = match &events[0] {
5958 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5961 _ => panic!("Unexpected event"),
5964 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5965 check_added_monitors!(nodes[2], 1);
5966 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5968 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5969 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5970 assert_eq!(process_htlc_forwards_event.len(), 2);
5971 match &process_htlc_forwards_event[0] {
5972 &Event::PendingHTLCsForwardable { .. } => {},
5973 _ => panic!("Unexpected event"),
5976 // In response, we call ChannelManager's process_pending_htlc_forwards
5977 nodes[1].node.process_pending_htlc_forwards();
5978 check_added_monitors!(nodes[1], 1);
5980 // This causes the HTLC to be failed backwards.
5981 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5982 assert_eq!(fail_event.len(), 1);
5983 let (fail_msg, commitment_signed) = match &fail_event[0] {
5984 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5985 assert_eq!(updates.update_add_htlcs.len(), 0);
5986 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5987 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5988 assert_eq!(updates.update_fail_htlcs.len(), 1);
5989 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5991 _ => panic!("Unexpected event"),
5994 // Pass the failure messages back to nodes[0].
5995 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5996 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5998 // Complete the HTLC failure+removal process.
5999 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6000 check_added_monitors!(nodes[0], 1);
6001 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6002 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6003 check_added_monitors!(nodes[1], 2);
6004 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6005 assert_eq!(final_raa_event.len(), 1);
6006 let raa = match &final_raa_event[0] {
6007 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6008 _ => panic!("Unexpected event"),
6010 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6011 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6012 check_added_monitors!(nodes[0], 1);
6015 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6016 // 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.
6017 //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.
6020 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6021 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6022 let chanmon_cfgs = create_chanmon_cfgs(2);
6023 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6024 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6025 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6026 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6028 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6029 route.paths[0].hops[0].fee_msat = 100;
6031 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6032 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6033 ), true, APIError::ChannelUnavailable { ref err },
6034 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6035 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6036 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6040 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6041 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6042 let chanmon_cfgs = create_chanmon_cfgs(2);
6043 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6044 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6045 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6046 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6048 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6049 route.paths[0].hops[0].fee_msat = 0;
6050 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6051 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6052 true, APIError::ChannelUnavailable { ref err },
6053 assert_eq!(err, "Cannot send 0-msat HTLC"));
6055 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6056 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6060 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6061 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6062 let chanmon_cfgs = create_chanmon_cfgs(2);
6063 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6064 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6065 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6066 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6068 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6069 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6070 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6071 check_added_monitors!(nodes[0], 1);
6072 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6073 updates.update_add_htlcs[0].amount_msat = 0;
6075 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6076 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6077 check_closed_broadcast!(nodes[1], true).unwrap();
6078 check_added_monitors!(nodes[1], 1);
6079 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6083 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6084 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6085 //It is enforced when constructing a route.
6086 let chanmon_cfgs = create_chanmon_cfgs(2);
6087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6089 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6090 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6092 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6093 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6094 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6095 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6096 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6097 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6098 ), true, APIError::InvalidRoute { ref err },
6099 assert_eq!(err, &"Channel CLTV overflowed?"));
6103 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6104 //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.
6105 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6106 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6107 let chanmon_cfgs = create_chanmon_cfgs(2);
6108 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6109 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6110 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6111 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6112 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6113 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6115 for i in 0..max_accepted_htlcs {
6116 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6117 let payment_event = {
6118 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6119 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6120 check_added_monitors!(nodes[0], 1);
6122 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6123 assert_eq!(events.len(), 1);
6124 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6125 assert_eq!(htlcs[0].htlc_id, i);
6129 SendEvent::from_event(events.remove(0))
6131 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6132 check_added_monitors!(nodes[1], 0);
6133 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6135 expect_pending_htlcs_forwardable!(nodes[1]);
6136 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6138 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6139 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6140 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6141 ), true, APIError::ChannelUnavailable { ref err },
6142 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6144 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6145 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6149 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6150 //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.
6151 let chanmon_cfgs = create_chanmon_cfgs(2);
6152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6154 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6155 let channel_value = 100000;
6156 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6157 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6159 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6161 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6162 // Manually create a route over our max in flight (which our router normally automatically
6164 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6165 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6166 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6167 ), true, APIError::ChannelUnavailable { ref err },
6168 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)));
6170 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6171 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);
6173 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6176 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6178 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6179 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6180 let chanmon_cfgs = create_chanmon_cfgs(2);
6181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6184 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6185 let htlc_minimum_msat: u64;
6187 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6188 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6189 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6190 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6193 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6194 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6195 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6196 check_added_monitors!(nodes[0], 1);
6197 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6198 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6199 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6200 assert!(nodes[1].node.list_channels().is_empty());
6201 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6202 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()));
6203 check_added_monitors!(nodes[1], 1);
6204 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6208 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6209 //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
6210 let chanmon_cfgs = create_chanmon_cfgs(2);
6211 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6212 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6213 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6214 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6216 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6217 let channel_reserve = chan_stat.channel_reserve_msat;
6218 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6219 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6220 // The 2* and +1 are for the fee spike reserve.
6221 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6223 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6224 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6225 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6226 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6227 check_added_monitors!(nodes[0], 1);
6228 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6230 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6231 // at this time channel-initiatee receivers are not required to enforce that senders
6232 // respect the fee_spike_reserve.
6233 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6234 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6236 assert!(nodes[1].node.list_channels().is_empty());
6237 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6238 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6239 check_added_monitors!(nodes[1], 1);
6240 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6244 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6245 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6246 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6247 let chanmon_cfgs = create_chanmon_cfgs(2);
6248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6250 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6251 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6253 let send_amt = 3999999;
6254 let (mut route, our_payment_hash, _, our_payment_secret) =
6255 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6256 route.paths[0].hops[0].fee_msat = send_amt;
6257 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6258 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6259 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6260 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6261 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6262 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6264 let mut msg = msgs::UpdateAddHTLC {
6268 payment_hash: our_payment_hash,
6269 cltv_expiry: htlc_cltv,
6270 onion_routing_packet: onion_packet.clone(),
6274 msg.htlc_id = i as u64;
6275 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6277 msg.htlc_id = (50) as u64;
6278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6280 assert!(nodes[1].node.list_channels().is_empty());
6281 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6282 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6283 check_added_monitors!(nodes[1], 1);
6284 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6288 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6289 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6290 let chanmon_cfgs = create_chanmon_cfgs(2);
6291 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6292 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6293 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6294 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6296 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6297 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6298 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6299 check_added_monitors!(nodes[0], 1);
6300 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6301 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;
6302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6304 assert!(nodes[1].node.list_channels().is_empty());
6305 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6306 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6307 check_added_monitors!(nodes[1], 1);
6308 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6312 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6313 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6314 let chanmon_cfgs = create_chanmon_cfgs(2);
6315 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6316 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6317 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6320 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6321 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6322 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6323 check_added_monitors!(nodes[0], 1);
6324 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6325 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6326 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6328 assert!(nodes[1].node.list_channels().is_empty());
6329 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6330 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6331 check_added_monitors!(nodes[1], 1);
6332 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6336 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6337 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6338 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6339 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6340 let chanmon_cfgs = create_chanmon_cfgs(2);
6341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6343 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6345 create_announced_chan_between_nodes(&nodes, 0, 1);
6346 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6347 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6348 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6349 check_added_monitors!(nodes[0], 1);
6350 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6351 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6353 //Disconnect and Reconnect
6354 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6355 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6356 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6357 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6358 assert_eq!(reestablish_1.len(), 1);
6359 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
6360 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6361 assert_eq!(reestablish_2.len(), 1);
6362 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6363 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6364 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6365 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6368 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6369 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6370 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6371 check_added_monitors!(nodes[1], 1);
6372 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6376 assert!(nodes[1].node.list_channels().is_empty());
6377 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6378 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6379 check_added_monitors!(nodes[1], 1);
6380 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6384 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6385 //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.
6387 let chanmon_cfgs = create_chanmon_cfgs(2);
6388 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6389 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6390 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6391 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6392 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6393 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6394 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6396 check_added_monitors!(nodes[0], 1);
6397 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6398 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6400 let update_msg = msgs::UpdateFulfillHTLC{
6403 payment_preimage: our_payment_preimage,
6406 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6408 assert!(nodes[0].node.list_channels().is_empty());
6409 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6410 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()));
6411 check_added_monitors!(nodes[0], 1);
6412 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6416 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6417 //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.
6419 let chanmon_cfgs = create_chanmon_cfgs(2);
6420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6422 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6423 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6425 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6426 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6427 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6428 check_added_monitors!(nodes[0], 1);
6429 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6430 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6432 let update_msg = msgs::UpdateFailHTLC{
6435 reason: msgs::OnionErrorPacket { data: Vec::new()},
6438 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6440 assert!(nodes[0].node.list_channels().is_empty());
6441 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6442 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()));
6443 check_added_monitors!(nodes[0], 1);
6444 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6448 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6449 //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.
6451 let chanmon_cfgs = create_chanmon_cfgs(2);
6452 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6453 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6454 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6455 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6457 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6458 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6459 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6460 check_added_monitors!(nodes[0], 1);
6461 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6463 let update_msg = msgs::UpdateFailMalformedHTLC{
6466 sha256_of_onion: [1; 32],
6467 failure_code: 0x8000,
6470 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6472 assert!(nodes[0].node.list_channels().is_empty());
6473 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6474 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()));
6475 check_added_monitors!(nodes[0], 1);
6476 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6480 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6481 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6483 let chanmon_cfgs = create_chanmon_cfgs(2);
6484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6486 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6487 create_announced_chan_between_nodes(&nodes, 0, 1);
6489 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6491 nodes[1].node.claim_funds(our_payment_preimage);
6492 check_added_monitors!(nodes[1], 1);
6493 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6495 let events = nodes[1].node.get_and_clear_pending_msg_events();
6496 assert_eq!(events.len(), 1);
6497 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6499 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, .. } } => {
6500 assert!(update_add_htlcs.is_empty());
6501 assert_eq!(update_fulfill_htlcs.len(), 1);
6502 assert!(update_fail_htlcs.is_empty());
6503 assert!(update_fail_malformed_htlcs.is_empty());
6504 assert!(update_fee.is_none());
6505 update_fulfill_htlcs[0].clone()
6507 _ => panic!("Unexpected event"),
6511 update_fulfill_msg.htlc_id = 1;
6513 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6515 assert!(nodes[0].node.list_channels().is_empty());
6516 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6517 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6518 check_added_monitors!(nodes[0], 1);
6519 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6523 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6524 //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.
6526 let chanmon_cfgs = create_chanmon_cfgs(2);
6527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530 create_announced_chan_between_nodes(&nodes, 0, 1);
6532 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6534 nodes[1].node.claim_funds(our_payment_preimage);
6535 check_added_monitors!(nodes[1], 1);
6536 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6538 let events = nodes[1].node.get_and_clear_pending_msg_events();
6539 assert_eq!(events.len(), 1);
6540 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6542 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, .. } } => {
6543 assert!(update_add_htlcs.is_empty());
6544 assert_eq!(update_fulfill_htlcs.len(), 1);
6545 assert!(update_fail_htlcs.is_empty());
6546 assert!(update_fail_malformed_htlcs.is_empty());
6547 assert!(update_fee.is_none());
6548 update_fulfill_htlcs[0].clone()
6550 _ => panic!("Unexpected event"),
6554 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6556 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6558 assert!(nodes[0].node.list_channels().is_empty());
6559 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6560 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6561 check_added_monitors!(nodes[0], 1);
6562 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6566 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6567 //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.
6569 let chanmon_cfgs = create_chanmon_cfgs(2);
6570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6575 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6576 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6577 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6578 check_added_monitors!(nodes[0], 1);
6580 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6583 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584 check_added_monitors!(nodes[1], 0);
6585 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6587 let events = nodes[1].node.get_and_clear_pending_msg_events();
6589 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6591 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, .. } } => {
6592 assert!(update_add_htlcs.is_empty());
6593 assert!(update_fulfill_htlcs.is_empty());
6594 assert!(update_fail_htlcs.is_empty());
6595 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6596 assert!(update_fee.is_none());
6597 update_fail_malformed_htlcs[0].clone()
6599 _ => panic!("Unexpected event"),
6602 update_msg.failure_code &= !0x8000;
6603 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6605 assert!(nodes[0].node.list_channels().is_empty());
6606 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6607 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6608 check_added_monitors!(nodes[0], 1);
6609 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6613 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6614 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6615 // * 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.
6617 let chanmon_cfgs = create_chanmon_cfgs(3);
6618 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6620 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6621 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6622 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6627 let mut payment_event = {
6628 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6629 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6630 check_added_monitors!(nodes[0], 1);
6631 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6632 assert_eq!(events.len(), 1);
6633 SendEvent::from_event(events.remove(0))
6635 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6636 check_added_monitors!(nodes[1], 0);
6637 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6638 expect_pending_htlcs_forwardable!(nodes[1]);
6639 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6640 assert_eq!(events_2.len(), 1);
6641 check_added_monitors!(nodes[1], 1);
6642 payment_event = SendEvent::from_event(events_2.remove(0));
6643 assert_eq!(payment_event.msgs.len(), 1);
6646 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6647 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6648 check_added_monitors!(nodes[2], 0);
6649 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6651 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6652 assert_eq!(events_3.len(), 1);
6653 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6655 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 } } => {
6656 assert!(update_add_htlcs.is_empty());
6657 assert!(update_fulfill_htlcs.is_empty());
6658 assert!(update_fail_htlcs.is_empty());
6659 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6660 assert!(update_fee.is_none());
6661 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6663 _ => panic!("Unexpected event"),
6667 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6669 check_added_monitors!(nodes[1], 0);
6670 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6671 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 }]);
6672 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6673 assert_eq!(events_4.len(), 1);
6675 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6677 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, .. } } => {
6678 assert!(update_add_htlcs.is_empty());
6679 assert!(update_fulfill_htlcs.is_empty());
6680 assert_eq!(update_fail_htlcs.len(), 1);
6681 assert!(update_fail_malformed_htlcs.is_empty());
6682 assert!(update_fee.is_none());
6684 _ => panic!("Unexpected event"),
6687 check_added_monitors!(nodes[1], 1);
6691 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6692 let chanmon_cfgs = create_chanmon_cfgs(3);
6693 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6694 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6695 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6696 create_announced_chan_between_nodes(&nodes, 0, 1);
6697 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6699 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6702 let mut payment_event = {
6703 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6704 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6705 check_added_monitors!(nodes[0], 1);
6706 SendEvent::from_node(&nodes[0])
6709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6710 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6711 expect_pending_htlcs_forwardable!(nodes[1]);
6712 check_added_monitors!(nodes[1], 1);
6713 payment_event = SendEvent::from_node(&nodes[1]);
6714 assert_eq!(payment_event.msgs.len(), 1);
6717 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6718 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6719 check_added_monitors!(nodes[2], 0);
6720 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6722 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6723 assert_eq!(events_3.len(), 1);
6725 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6726 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6727 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6728 update_msg.failure_code |= 0x2000;
6730 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6731 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6733 _ => panic!("Unexpected event"),
6736 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6737 vec![HTLCDestination::NextHopChannel {
6738 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6739 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6740 assert_eq!(events_4.len(), 1);
6741 check_added_monitors!(nodes[1], 1);
6744 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6745 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6746 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6748 _ => panic!("Unexpected event"),
6751 let events_5 = nodes[0].node.get_and_clear_pending_events();
6752 assert_eq!(events_5.len(), 2);
6754 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6755 // the node originating the error to its next hop.
6757 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6759 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6760 assert!(is_permanent);
6761 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6763 _ => panic!("Unexpected event"),
6766 Event::PaymentFailed { payment_hash, .. } => {
6767 assert_eq!(payment_hash, our_payment_hash);
6769 _ => panic!("Unexpected event"),
6772 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6775 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6776 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6777 // 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
6778 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6780 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6781 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6784 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6785 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6787 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6788 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6790 // We route 2 dust-HTLCs between A and B
6791 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6792 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6793 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6795 // Cache one local commitment tx as previous
6796 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6798 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6799 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6800 check_added_monitors!(nodes[1], 0);
6801 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6802 check_added_monitors!(nodes[1], 1);
6804 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6805 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6806 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6807 check_added_monitors!(nodes[0], 1);
6809 // Cache one local commitment tx as lastest
6810 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6812 let events = nodes[0].node.get_and_clear_pending_msg_events();
6814 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6815 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6817 _ => panic!("Unexpected event"),
6820 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6821 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6823 _ => panic!("Unexpected event"),
6826 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6827 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6828 if announce_latest {
6829 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6831 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6834 check_closed_broadcast!(nodes[0], true);
6835 check_added_monitors!(nodes[0], 1);
6836 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6838 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6839 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6840 let events = nodes[0].node.get_and_clear_pending_events();
6841 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6842 assert_eq!(events.len(), 4);
6843 let mut first_failed = false;
6844 for event in events {
6846 Event::PaymentPathFailed { payment_hash, .. } => {
6847 if payment_hash == payment_hash_1 {
6848 assert!(!first_failed);
6849 first_failed = true;
6851 assert_eq!(payment_hash, payment_hash_2);
6854 Event::PaymentFailed { .. } => {}
6855 _ => panic!("Unexpected event"),
6861 fn test_failure_delay_dust_htlc_local_commitment() {
6862 do_test_failure_delay_dust_htlc_local_commitment(true);
6863 do_test_failure_delay_dust_htlc_local_commitment(false);
6866 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6867 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6868 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6869 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6870 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6871 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6872 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6874 let chanmon_cfgs = create_chanmon_cfgs(3);
6875 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6876 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6877 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6878 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6880 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6881 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6883 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6884 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6886 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6887 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6889 // We revoked bs_commitment_tx
6891 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6892 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6895 let mut timeout_tx = Vec::new();
6897 // We fail dust-HTLC 1 by broadcast of local commitment tx
6898 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6899 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6900 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6901 expect_payment_failed!(nodes[0], dust_hash, false);
6903 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6904 check_closed_broadcast!(nodes[0], true);
6905 check_added_monitors!(nodes[0], 1);
6906 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6907 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6908 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6909 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6910 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6911 mine_transaction(&nodes[0], &timeout_tx[0]);
6912 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6913 expect_payment_failed!(nodes[0], non_dust_hash, false);
6915 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6916 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6917 check_closed_broadcast!(nodes[0], true);
6918 check_added_monitors!(nodes[0], 1);
6919 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6920 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6922 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6923 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6924 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6925 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6926 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6927 // dust HTLC should have been failed.
6928 expect_payment_failed!(nodes[0], dust_hash, false);
6931 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6933 assert_eq!(timeout_tx[0].lock_time.0, 11);
6935 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6936 mine_transaction(&nodes[0], &timeout_tx[0]);
6937 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6938 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6939 expect_payment_failed!(nodes[0], non_dust_hash, false);
6944 fn test_sweep_outbound_htlc_failure_update() {
6945 do_test_sweep_outbound_htlc_failure_update(false, true);
6946 do_test_sweep_outbound_htlc_failure_update(false, false);
6947 do_test_sweep_outbound_htlc_failure_update(true, false);
6951 fn test_user_configurable_csv_delay() {
6952 // We test our channel constructors yield errors when we pass them absurd csv delay
6954 let mut low_our_to_self_config = UserConfig::default();
6955 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6956 let mut high_their_to_self_config = UserConfig::default();
6957 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6958 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6959 let chanmon_cfgs = create_chanmon_cfgs(2);
6960 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6961 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6962 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6964 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6965 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6966 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6967 &low_our_to_self_config, 0, 42)
6970 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())); },
6971 _ => panic!("Unexpected event"),
6973 } else { assert!(false) }
6975 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6976 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6977 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6978 open_channel.to_self_delay = 200;
6979 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6980 &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,
6981 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6984 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())); },
6985 _ => panic!("Unexpected event"),
6987 } else { assert!(false); }
6989 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6990 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6991 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()));
6992 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6993 accept_channel.to_self_delay = 200;
6994 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6996 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6998 &ErrorAction::SendErrorMessage { ref msg } => {
6999 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()));
7000 reason_msg = msg.data.clone();
7004 } else { panic!(); }
7005 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7007 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7008 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7009 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7010 open_channel.to_self_delay = 200;
7011 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7012 &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,
7013 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7016 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())); },
7017 _ => panic!("Unexpected event"),
7019 } else { assert!(false); }
7023 fn test_check_htlc_underpaying() {
7024 // Send payment through A -> B but A is maliciously
7025 // sending a probe payment (i.e less than expected value0
7026 // to B, B should refuse payment.
7028 let chanmon_cfgs = create_chanmon_cfgs(2);
7029 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7030 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7031 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7033 // Create some initial channels
7034 create_announced_chan_between_nodes(&nodes, 0, 1);
7036 let scorer = test_utils::TestScorer::new();
7037 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7038 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();
7039 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();
7040 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7041 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7042 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7043 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7044 check_added_monitors!(nodes[0], 1);
7046 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7047 assert_eq!(events.len(), 1);
7048 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7049 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7050 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7052 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7053 // and then will wait a second random delay before failing the HTLC back:
7054 expect_pending_htlcs_forwardable!(nodes[1]);
7055 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7057 // Node 3 is expecting payment of 100_000 but received 10_000,
7058 // it should fail htlc like we didn't know the preimage.
7059 nodes[1].node.process_pending_htlc_forwards();
7061 let events = nodes[1].node.get_and_clear_pending_msg_events();
7062 assert_eq!(events.len(), 1);
7063 let (update_fail_htlc, commitment_signed) = match events[0] {
7064 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 } } => {
7065 assert!(update_add_htlcs.is_empty());
7066 assert!(update_fulfill_htlcs.is_empty());
7067 assert_eq!(update_fail_htlcs.len(), 1);
7068 assert!(update_fail_malformed_htlcs.is_empty());
7069 assert!(update_fee.is_none());
7070 (update_fail_htlcs[0].clone(), commitment_signed)
7072 _ => panic!("Unexpected event"),
7074 check_added_monitors!(nodes[1], 1);
7076 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7077 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7079 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7080 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7081 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7082 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7086 fn test_announce_disable_channels() {
7087 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7088 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7090 let chanmon_cfgs = create_chanmon_cfgs(2);
7091 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7092 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7093 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7095 create_announced_chan_between_nodes(&nodes, 0, 1);
7096 create_announced_chan_between_nodes(&nodes, 1, 0);
7097 create_announced_chan_between_nodes(&nodes, 0, 1);
7100 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7101 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7103 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7104 nodes[0].node.timer_tick_occurred();
7106 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7107 assert_eq!(msg_events.len(), 3);
7108 let mut chans_disabled = HashMap::new();
7109 for e in msg_events {
7111 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7112 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7113 // Check that each channel gets updated exactly once
7114 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7115 panic!("Generated ChannelUpdate for wrong chan!");
7118 _ => panic!("Unexpected event"),
7122 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
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 { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7126 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7127 assert_eq!(reestablish_2.len(), 3);
7129 // Reestablish chan_1
7130 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7131 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7132 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7133 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7134 // Reestablish chan_2
7135 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7136 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7137 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7138 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7139 // Reestablish chan_3
7140 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7141 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7142 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7143 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7145 for _ in 0..ENABLE_GOSSIP_TICKS {
7146 nodes[0].node.timer_tick_occurred();
7148 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7149 nodes[0].node.timer_tick_occurred();
7150 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7151 assert_eq!(msg_events.len(), 3);
7152 for e in msg_events {
7154 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7155 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7156 match chans_disabled.remove(&msg.contents.short_channel_id) {
7157 // Each update should have a higher timestamp than the previous one, replacing
7159 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7160 None => panic!("Generated ChannelUpdate for wrong chan!"),
7163 _ => panic!("Unexpected event"),
7166 // Check that each channel gets updated exactly once
7167 assert!(chans_disabled.is_empty());
7171 fn test_bump_penalty_txn_on_revoked_commitment() {
7172 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7173 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7175 let chanmon_cfgs = create_chanmon_cfgs(2);
7176 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7177 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7178 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7180 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7182 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7183 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7184 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7185 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7186 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7188 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7189 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7190 assert_eq!(revoked_txn[0].output.len(), 4);
7191 assert_eq!(revoked_txn[0].input.len(), 1);
7192 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7193 let revoked_txid = revoked_txn[0].txid();
7195 let mut penalty_sum = 0;
7196 for outp in revoked_txn[0].output.iter() {
7197 if outp.script_pubkey.is_v0_p2wsh() {
7198 penalty_sum += outp.value;
7202 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7203 let header_114 = connect_blocks(&nodes[1], 14);
7205 // Actually revoke tx by claiming a HTLC
7206 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7207 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7208 check_added_monitors!(nodes[1], 1);
7210 // One or more justice tx should have been broadcast, check it
7214 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7215 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7216 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7217 assert_eq!(node_txn[0].output.len(), 1);
7218 check_spends!(node_txn[0], revoked_txn[0]);
7219 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7220 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7221 penalty_1 = node_txn[0].txid();
7225 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7226 connect_blocks(&nodes[1], 15);
7227 let mut penalty_2 = penalty_1;
7228 let mut feerate_2 = 0;
7230 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7231 assert_eq!(node_txn.len(), 1);
7232 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7233 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7234 assert_eq!(node_txn[0].output.len(), 1);
7235 check_spends!(node_txn[0], revoked_txn[0]);
7236 penalty_2 = node_txn[0].txid();
7237 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7238 assert_ne!(penalty_2, penalty_1);
7239 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7240 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7241 // Verify 25% bump heuristic
7242 assert!(feerate_2 * 100 >= feerate_1 * 125);
7246 assert_ne!(feerate_2, 0);
7248 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7249 connect_blocks(&nodes[1], 1);
7251 let mut feerate_3 = 0;
7253 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7254 assert_eq!(node_txn.len(), 1);
7255 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7256 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7257 assert_eq!(node_txn[0].output.len(), 1);
7258 check_spends!(node_txn[0], revoked_txn[0]);
7259 penalty_3 = node_txn[0].txid();
7260 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7261 assert_ne!(penalty_3, penalty_2);
7262 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7263 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7264 // Verify 25% bump heuristic
7265 assert!(feerate_3 * 100 >= feerate_2 * 125);
7269 assert_ne!(feerate_3, 0);
7271 nodes[1].node.get_and_clear_pending_events();
7272 nodes[1].node.get_and_clear_pending_msg_events();
7276 fn test_bump_penalty_txn_on_revoked_htlcs() {
7277 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7278 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7280 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7281 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7284 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7286 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7287 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7288 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7289 let scorer = test_utils::TestScorer::new();
7290 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7291 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7292 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7293 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7294 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7295 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7296 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7297 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7299 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7300 assert_eq!(revoked_local_txn[0].input.len(), 1);
7301 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7303 // Revoke local commitment tx
7304 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7306 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7307 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7308 check_closed_broadcast!(nodes[1], true);
7309 check_added_monitors!(nodes[1], 1);
7310 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7311 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7313 let revoked_htlc_txn = {
7314 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7315 assert_eq!(txn.len(), 2);
7317 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7318 assert_eq!(txn[0].input.len(), 1);
7319 check_spends!(txn[0], revoked_local_txn[0]);
7321 assert_eq!(txn[1].input.len(), 1);
7322 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7323 assert_eq!(txn[1].output.len(), 1);
7324 check_spends!(txn[1], revoked_local_txn[0]);
7329 // Broadcast set of revoked txn on A
7330 let hash_128 = connect_blocks(&nodes[0], 40);
7331 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7332 connect_block(&nodes[0], &block_11);
7333 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7334 connect_block(&nodes[0], &block_129);
7335 let events = nodes[0].node.get_and_clear_pending_events();
7336 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7337 match events.last().unwrap() {
7338 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7339 _ => panic!("Unexpected event"),
7345 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7346 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7347 // Verify claim tx are spending revoked HTLC txn
7349 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7350 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7351 // which are included in the same block (they are broadcasted because we scan the
7352 // transactions linearly and generate claims as we go, they likely should be removed in the
7354 assert_eq!(node_txn[0].input.len(), 1);
7355 check_spends!(node_txn[0], revoked_local_txn[0]);
7356 assert_eq!(node_txn[1].input.len(), 1);
7357 check_spends!(node_txn[1], revoked_local_txn[0]);
7358 assert_eq!(node_txn[2].input.len(), 1);
7359 check_spends!(node_txn[2], revoked_local_txn[0]);
7361 // Each of the three justice transactions claim a separate (single) output of the three
7362 // available, which we check here:
7363 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7364 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7365 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7367 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7368 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7370 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7371 // output, checked above).
7372 assert_eq!(node_txn[3].input.len(), 2);
7373 assert_eq!(node_txn[3].output.len(), 1);
7374 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7376 first = node_txn[3].txid();
7377 // Store both feerates for later comparison
7378 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7379 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7380 penalty_txn = vec![node_txn[2].clone()];
7384 // Connect one more block to see if bumped penalty are issued for HTLC txn
7385 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7386 connect_block(&nodes[0], &block_130);
7387 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7388 connect_block(&nodes[0], &block_131);
7390 // Few more blocks to confirm penalty txn
7391 connect_blocks(&nodes[0], 4);
7392 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7393 let header_144 = connect_blocks(&nodes[0], 9);
7395 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7396 assert_eq!(node_txn.len(), 1);
7398 assert_eq!(node_txn[0].input.len(), 2);
7399 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7400 // Verify bumped tx is different and 25% bump heuristic
7401 assert_ne!(first, node_txn[0].txid());
7402 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7403 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7404 assert!(feerate_2 * 100 > feerate_1 * 125);
7405 let txn = vec![node_txn[0].clone()];
7409 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7410 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7411 connect_blocks(&nodes[0], 20);
7413 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7414 // We verify than no new transaction has been broadcast because previously
7415 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7416 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7417 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7418 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7419 // up bumped justice generation.
7420 assert_eq!(node_txn.len(), 0);
7423 check_closed_broadcast!(nodes[0], true);
7424 check_added_monitors!(nodes[0], 1);
7428 fn test_bump_penalty_txn_on_remote_commitment() {
7429 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7430 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7433 // Provide preimage for one
7434 // Check aggregation
7436 let chanmon_cfgs = create_chanmon_cfgs(2);
7437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7439 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7441 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7442 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7443 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7445 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7446 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7447 assert_eq!(remote_txn[0].output.len(), 4);
7448 assert_eq!(remote_txn[0].input.len(), 1);
7449 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7451 // Claim a HTLC without revocation (provide B monitor with preimage)
7452 nodes[1].node.claim_funds(payment_preimage);
7453 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7454 mine_transaction(&nodes[1], &remote_txn[0]);
7455 check_added_monitors!(nodes[1], 2);
7456 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7458 // One or more claim tx should have been broadcast, check it
7462 let feerate_timeout;
7463 let feerate_preimage;
7465 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7466 // 3 transactions including:
7467 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7468 assert_eq!(node_txn.len(), 3);
7469 assert_eq!(node_txn[0].input.len(), 1);
7470 assert_eq!(node_txn[1].input.len(), 1);
7471 assert_eq!(node_txn[2].input.len(), 1);
7472 check_spends!(node_txn[0], remote_txn[0]);
7473 check_spends!(node_txn[1], remote_txn[0]);
7474 check_spends!(node_txn[2], remote_txn[0]);
7476 preimage = node_txn[0].txid();
7477 let index = node_txn[0].input[0].previous_output.vout;
7478 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7479 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7481 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7482 (node_txn[2].clone(), node_txn[1].clone())
7484 (node_txn[1].clone(), node_txn[2].clone())
7487 preimage_bump = preimage_bump_tx;
7488 check_spends!(preimage_bump, remote_txn[0]);
7489 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7491 timeout = timeout_tx.txid();
7492 let index = timeout_tx.input[0].previous_output.vout;
7493 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7494 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7498 assert_ne!(feerate_timeout, 0);
7499 assert_ne!(feerate_preimage, 0);
7501 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7502 connect_blocks(&nodes[1], 1);
7504 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7505 assert_eq!(node_txn.len(), 1);
7506 assert_eq!(node_txn[0].input.len(), 1);
7507 assert_eq!(preimage_bump.input.len(), 1);
7508 check_spends!(node_txn[0], remote_txn[0]);
7509 check_spends!(preimage_bump, remote_txn[0]);
7511 let index = preimage_bump.input[0].previous_output.vout;
7512 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7513 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7514 assert!(new_feerate * 100 > feerate_timeout * 125);
7515 assert_ne!(timeout, preimage_bump.txid());
7517 let index = node_txn[0].input[0].previous_output.vout;
7518 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7519 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7520 assert!(new_feerate * 100 > feerate_preimage * 125);
7521 assert_ne!(preimage, node_txn[0].txid());
7526 nodes[1].node.get_and_clear_pending_events();
7527 nodes[1].node.get_and_clear_pending_msg_events();
7531 fn test_counterparty_raa_skip_no_crash() {
7532 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7533 // commitment transaction, we would have happily carried on and provided them the next
7534 // commitment transaction based on one RAA forward. This would probably eventually have led to
7535 // channel closure, but it would not have resulted in funds loss. Still, our
7536 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7537 // check simply that the channel is closed in response to such an RAA, but don't check whether
7538 // we decide to punish our counterparty for revoking their funds (as we don't currently
7540 let chanmon_cfgs = create_chanmon_cfgs(2);
7541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7543 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7544 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7546 let per_commitment_secret;
7547 let next_per_commitment_point;
7549 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7550 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7551 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7553 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7555 // Make signer believe we got a counterparty signature, so that it allows the revocation
7556 keys.get_enforcement_state().last_holder_commitment -= 1;
7557 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7559 // Must revoke without gaps
7560 keys.get_enforcement_state().last_holder_commitment -= 1;
7561 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7563 keys.get_enforcement_state().last_holder_commitment -= 1;
7564 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7565 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7568 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7569 &msgs::RevokeAndACK {
7571 per_commitment_secret,
7572 next_per_commitment_point,
7574 next_local_nonce: None,
7576 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7577 check_added_monitors!(nodes[1], 1);
7578 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7582 fn test_bump_txn_sanitize_tracking_maps() {
7583 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7584 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7586 let chanmon_cfgs = create_chanmon_cfgs(2);
7587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7589 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7591 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7592 // Lock HTLC in both directions
7593 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7594 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7596 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7597 assert_eq!(revoked_local_txn[0].input.len(), 1);
7598 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7600 // Revoke local commitment tx
7601 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7603 // Broadcast set of revoked txn on A
7604 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7605 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7606 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7608 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7609 check_closed_broadcast!(nodes[0], true);
7610 check_added_monitors!(nodes[0], 1);
7611 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7613 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7614 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7615 check_spends!(node_txn[0], revoked_local_txn[0]);
7616 check_spends!(node_txn[1], revoked_local_txn[0]);
7617 check_spends!(node_txn[2], revoked_local_txn[0]);
7618 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7622 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7623 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7625 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7626 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7627 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7632 fn test_channel_conf_timeout() {
7633 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7634 // confirm within 2016 blocks, as recommended by BOLT 2.
7635 let chanmon_cfgs = create_chanmon_cfgs(2);
7636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7638 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7640 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7642 // The outbound node should wait forever for confirmation:
7643 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7644 // copied here instead of directly referencing the constant.
7645 connect_blocks(&nodes[0], 2016);
7646 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7648 // The inbound node should fail the channel after exactly 2016 blocks
7649 connect_blocks(&nodes[1], 2015);
7650 check_added_monitors!(nodes[1], 0);
7651 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7653 connect_blocks(&nodes[1], 1);
7654 check_added_monitors!(nodes[1], 1);
7655 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7656 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7657 assert_eq!(close_ev.len(), 1);
7659 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7660 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7661 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7663 _ => panic!("Unexpected event"),
7668 fn test_override_channel_config() {
7669 let chanmon_cfgs = create_chanmon_cfgs(2);
7670 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7671 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7672 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7674 // Node0 initiates a channel to node1 using the override config.
7675 let mut override_config = UserConfig::default();
7676 override_config.channel_handshake_config.our_to_self_delay = 200;
7678 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7680 // Assert the channel created by node0 is using the override config.
7681 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7682 assert_eq!(res.channel_flags, 0);
7683 assert_eq!(res.to_self_delay, 200);
7687 fn test_override_0msat_htlc_minimum() {
7688 let mut zero_config = UserConfig::default();
7689 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7690 let chanmon_cfgs = create_chanmon_cfgs(2);
7691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7693 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7695 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7696 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7697 assert_eq!(res.htlc_minimum_msat, 1);
7699 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7700 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7701 assert_eq!(res.htlc_minimum_msat, 1);
7705 fn test_channel_update_has_correct_htlc_maximum_msat() {
7706 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7707 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7708 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7709 // 90% of the `channel_value`.
7710 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7712 let mut config_30_percent = UserConfig::default();
7713 config_30_percent.channel_handshake_config.announced_channel = true;
7714 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7715 let mut config_50_percent = UserConfig::default();
7716 config_50_percent.channel_handshake_config.announced_channel = true;
7717 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7718 let mut config_95_percent = UserConfig::default();
7719 config_95_percent.channel_handshake_config.announced_channel = true;
7720 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7721 let mut config_100_percent = UserConfig::default();
7722 config_100_percent.channel_handshake_config.announced_channel = true;
7723 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7725 let chanmon_cfgs = create_chanmon_cfgs(4);
7726 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7727 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)]);
7728 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7730 let channel_value_satoshis = 100000;
7731 let channel_value_msat = channel_value_satoshis * 1000;
7732 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7733 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7734 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7736 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7737 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7739 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7740 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7741 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7742 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7743 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7744 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7746 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7747 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7749 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7750 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7751 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7753 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7757 fn test_manually_accept_inbound_channel_request() {
7758 let mut manually_accept_conf = UserConfig::default();
7759 manually_accept_conf.manually_accept_inbound_channels = true;
7760 let chanmon_cfgs = create_chanmon_cfgs(2);
7761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7763 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7765 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7766 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7768 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7770 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7771 // accepting the inbound channel request.
7772 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7774 let events = nodes[1].node.get_and_clear_pending_events();
7776 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7777 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7779 _ => panic!("Unexpected event"),
7782 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7783 assert_eq!(accept_msg_ev.len(), 1);
7785 match accept_msg_ev[0] {
7786 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7787 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7789 _ => panic!("Unexpected event"),
7792 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7794 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7795 assert_eq!(close_msg_ev.len(), 1);
7797 let events = nodes[1].node.get_and_clear_pending_events();
7799 Event::ChannelClosed { user_channel_id, .. } => {
7800 assert_eq!(user_channel_id, 23);
7802 _ => panic!("Unexpected event"),
7807 fn test_manually_reject_inbound_channel_request() {
7808 let mut manually_accept_conf = UserConfig::default();
7809 manually_accept_conf.manually_accept_inbound_channels = true;
7810 let chanmon_cfgs = create_chanmon_cfgs(2);
7811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7813 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7815 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7816 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7818 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7820 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7821 // rejecting the inbound channel request.
7822 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7824 let events = nodes[1].node.get_and_clear_pending_events();
7826 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7827 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7829 _ => panic!("Unexpected event"),
7832 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7833 assert_eq!(close_msg_ev.len(), 1);
7835 match close_msg_ev[0] {
7836 MessageSendEvent::HandleError { ref node_id, .. } => {
7837 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7839 _ => panic!("Unexpected event"),
7841 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7845 fn test_reject_funding_before_inbound_channel_accepted() {
7846 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7847 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7848 // the node operator before the counterparty sends a `FundingCreated` message. If a
7849 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7850 // and the channel should be closed.
7851 let mut manually_accept_conf = UserConfig::default();
7852 manually_accept_conf.manually_accept_inbound_channels = true;
7853 let chanmon_cfgs = create_chanmon_cfgs(2);
7854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7856 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7858 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7859 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7860 let temp_channel_id = res.temporary_channel_id;
7862 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7864 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7865 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7867 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7868 nodes[1].node.get_and_clear_pending_events();
7870 // Get the `AcceptChannel` message of `nodes[1]` without calling
7871 // `ChannelManager::accept_inbound_channel`, which generates a
7872 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7873 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7874 // succeed when `nodes[0]` is passed to it.
7875 let accept_chan_msg = {
7876 let mut node_1_per_peer_lock;
7877 let mut node_1_peer_state_lock;
7878 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7879 channel.get_accept_channel_message()
7881 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7883 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7885 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7886 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7888 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7889 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7891 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7892 assert_eq!(close_msg_ev.len(), 1);
7894 let expected_err = "FundingCreated message received before the channel was accepted";
7895 match close_msg_ev[0] {
7896 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7897 assert_eq!(msg.channel_id, temp_channel_id);
7898 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7899 assert_eq!(msg.data, expected_err);
7901 _ => panic!("Unexpected event"),
7904 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7908 fn test_can_not_accept_inbound_channel_twice() {
7909 let mut manually_accept_conf = UserConfig::default();
7910 manually_accept_conf.manually_accept_inbound_channels = true;
7911 let chanmon_cfgs = create_chanmon_cfgs(2);
7912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7914 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7916 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7917 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7919 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7921 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7922 // accepting the inbound channel request.
7923 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7925 let events = nodes[1].node.get_and_clear_pending_events();
7927 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7928 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7929 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7931 Err(APIError::APIMisuseError { err }) => {
7932 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7934 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7935 Err(_) => panic!("Unexpected Error"),
7938 _ => panic!("Unexpected event"),
7941 // Ensure that the channel wasn't closed after attempting to accept it twice.
7942 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7943 assert_eq!(accept_msg_ev.len(), 1);
7945 match accept_msg_ev[0] {
7946 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7947 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7949 _ => panic!("Unexpected event"),
7954 fn test_can_not_accept_unknown_inbound_channel() {
7955 let chanmon_cfg = create_chanmon_cfgs(2);
7956 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7957 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7958 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7960 let unknown_channel_id = [0; 32];
7961 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7963 Err(APIError::ChannelUnavailable { err }) => {
7964 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()));
7966 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7967 Err(_) => panic!("Unexpected Error"),
7972 fn test_onion_value_mpp_set_calculation() {
7973 // Test that we use the onion value `amt_to_forward` when
7974 // calculating whether we've reached the `total_msat` of an MPP
7975 // by having a routing node forward more than `amt_to_forward`
7976 // and checking that the receiving node doesn't generate
7977 // a PaymentClaimable event too early
7979 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7980 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7981 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7982 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7984 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7985 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7986 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7987 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7989 let total_msat = 100_000;
7990 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7991 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7992 let sample_path = route.paths.pop().unwrap();
7994 let mut path_1 = sample_path.clone();
7995 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7996 path_1.hops[0].short_channel_id = chan_1_id;
7997 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7998 path_1.hops[1].short_channel_id = chan_3_id;
7999 path_1.hops[1].fee_msat = 100_000;
8000 route.paths.push(path_1);
8002 let mut path_2 = sample_path.clone();
8003 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8004 path_2.hops[0].short_channel_id = chan_2_id;
8005 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8006 path_2.hops[1].short_channel_id = chan_4_id;
8007 path_2.hops[1].fee_msat = 1_000;
8008 route.paths.push(path_2);
8011 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8012 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8013 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8014 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8015 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8016 check_added_monitors!(nodes[0], expected_paths.len());
8018 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8019 assert_eq!(events.len(), expected_paths.len());
8022 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8023 let mut payment_event = SendEvent::from_event(ev);
8024 let mut prev_node = &nodes[0];
8026 for (idx, &node) in expected_paths[0].iter().enumerate() {
8027 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8029 if idx == 0 { // routing node
8030 let session_priv = [3; 32];
8031 let height = nodes[0].best_block_info().1;
8032 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8033 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8034 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8035 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8036 // Edit amt_to_forward to simulate the sender having set
8037 // the final amount and the routing node taking less fee
8038 onion_payloads[1].amt_to_forward = 99_000;
8039 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8040 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8043 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8044 check_added_monitors!(node, 0);
8045 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8046 expect_pending_htlcs_forwardable!(node);
8049 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8050 assert_eq!(events_2.len(), 1);
8051 check_added_monitors!(node, 1);
8052 payment_event = SendEvent::from_event(events_2.remove(0));
8053 assert_eq!(payment_event.msgs.len(), 1);
8055 let events_2 = node.node.get_and_clear_pending_events();
8056 assert!(events_2.is_empty());
8063 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8064 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8066 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8069 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8071 let routing_node_count = msat_amounts.len();
8072 let node_count = routing_node_count + 2;
8074 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8075 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8076 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8077 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8082 // Create channels for each amount
8083 let mut expected_paths = Vec::with_capacity(routing_node_count);
8084 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8085 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8086 for i in 0..routing_node_count {
8087 let routing_node = 2 + i;
8088 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8089 src_chan_ids.push(src_chan_id);
8090 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8091 dst_chan_ids.push(dst_chan_id);
8092 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8093 expected_paths.push(path);
8095 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8097 // Create a route for each amount
8098 let example_amount = 100000;
8099 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);
8100 let sample_path = route.paths.pop().unwrap();
8101 for i in 0..routing_node_count {
8102 let routing_node = 2 + i;
8103 let mut path = sample_path.clone();
8104 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8105 path.hops[0].short_channel_id = src_chan_ids[i];
8106 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8107 path.hops[1].short_channel_id = dst_chan_ids[i];
8108 path.hops[1].fee_msat = msat_amounts[i];
8109 route.paths.push(path);
8112 // Send payment with manually set total_msat
8113 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8114 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8115 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8116 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8117 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8118 check_added_monitors!(nodes[src_idx], expected_paths.len());
8120 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8121 assert_eq!(events.len(), expected_paths.len());
8122 let mut amount_received = 0;
8123 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8124 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8126 let current_path_amount = msat_amounts[path_idx];
8127 amount_received += current_path_amount;
8128 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8129 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8132 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8136 fn test_overshoot_mpp() {
8137 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8138 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8142 fn test_simple_mpp() {
8143 // Simple test of sending a multi-path payment.
8144 let chanmon_cfgs = create_chanmon_cfgs(4);
8145 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8146 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8147 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8149 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8150 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8151 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8152 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8154 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8155 let path = route.paths[0].clone();
8156 route.paths.push(path);
8157 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8158 route.paths[0].hops[0].short_channel_id = chan_1_id;
8159 route.paths[0].hops[1].short_channel_id = chan_3_id;
8160 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8161 route.paths[1].hops[0].short_channel_id = chan_2_id;
8162 route.paths[1].hops[1].short_channel_id = chan_4_id;
8163 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8164 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8168 fn test_preimage_storage() {
8169 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8170 let chanmon_cfgs = create_chanmon_cfgs(2);
8171 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8172 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8173 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8175 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8178 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8179 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8180 nodes[0].node.send_payment_with_route(&route, payment_hash,
8181 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8182 check_added_monitors!(nodes[0], 1);
8183 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8184 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8185 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8186 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8188 // Note that after leaving the above scope we have no knowledge of any arguments or return
8189 // values from previous calls.
8190 expect_pending_htlcs_forwardable!(nodes[1]);
8191 let events = nodes[1].node.get_and_clear_pending_events();
8192 assert_eq!(events.len(), 1);
8194 Event::PaymentClaimable { ref purpose, .. } => {
8196 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8197 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8199 _ => panic!("expected PaymentPurpose::InvoicePayment")
8202 _ => panic!("Unexpected event"),
8207 #[allow(deprecated)]
8208 fn test_secret_timeout() {
8209 // Simple test of payment secret storage time outs. After
8210 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
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;
8218 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8220 // We should fail to register the same payment hash twice, at least until we've connected a
8221 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8222 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8223 assert_eq!(err, "Duplicate payment hash");
8224 } else { panic!(); }
8226 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8227 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8229 connect_block(&nodes[1], &block);
8230 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8231 assert_eq!(err, "Duplicate payment hash");
8232 } else { panic!(); }
8234 // If we then connect the second block, we should be able to register the same payment hash
8235 // again (this time getting a new payment secret).
8236 block.header.prev_blockhash = block.header.block_hash();
8237 block.header.time += 1;
8238 connect_block(&nodes[1], &block);
8239 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8240 assert_ne!(payment_secret_1, our_payment_secret);
8243 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8244 nodes[0].node.send_payment_with_route(&route, payment_hash,
8245 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8246 check_added_monitors!(nodes[0], 1);
8247 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8248 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8249 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8250 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8252 // Note that after leaving the above scope we have no knowledge of any arguments or return
8253 // values from previous calls.
8254 expect_pending_htlcs_forwardable!(nodes[1]);
8255 let events = nodes[1].node.get_and_clear_pending_events();
8256 assert_eq!(events.len(), 1);
8258 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8259 assert!(payment_preimage.is_none());
8260 assert_eq!(payment_secret, our_payment_secret);
8261 // We don't actually have the payment preimage with which to claim this payment!
8263 _ => panic!("Unexpected event"),
8268 fn test_bad_secret_hash() {
8269 // Simple test of unregistered payment hash/invalid payment secret handling
8270 let chanmon_cfgs = create_chanmon_cfgs(2);
8271 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8272 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8273 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8275 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8277 let random_payment_hash = PaymentHash([42; 32]);
8278 let random_payment_secret = PaymentSecret([43; 32]);
8279 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8280 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8282 // All the below cases should end up being handled exactly identically, so we macro the
8283 // resulting events.
8284 macro_rules! handle_unknown_invalid_payment_data {
8285 ($payment_hash: expr) => {
8286 check_added_monitors!(nodes[0], 1);
8287 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8288 let payment_event = SendEvent::from_event(events.pop().unwrap());
8289 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8290 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8292 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8293 // again to process the pending backwards-failure of the HTLC
8294 expect_pending_htlcs_forwardable!(nodes[1]);
8295 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8296 check_added_monitors!(nodes[1], 1);
8298 // We should fail the payment back
8299 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8300 match events.pop().unwrap() {
8301 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8303 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8305 _ => panic!("Unexpected event"),
8310 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8311 // Error data is the HTLC value (100,000) and current block height
8312 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8314 // Send a payment with the right payment hash but the wrong payment secret
8315 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8316 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8317 handle_unknown_invalid_payment_data!(our_payment_hash);
8318 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8320 // Send a payment with a random payment hash, but the right payment secret
8321 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8322 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8323 handle_unknown_invalid_payment_data!(random_payment_hash);
8324 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8326 // Send a payment with a random payment hash and random payment secret
8327 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8328 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8329 handle_unknown_invalid_payment_data!(random_payment_hash);
8330 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8334 fn test_update_err_monitor_lockdown() {
8335 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8336 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8337 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8340 // This scenario may happen in a watchtower setup, where watchtower process a block height
8341 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8342 // commitment at same time.
8344 let chanmon_cfgs = create_chanmon_cfgs(2);
8345 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8346 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8347 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8349 // Create some initial channel
8350 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8351 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8353 // Rebalance the network to generate htlc in the two directions
8354 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8356 // Route a HTLC from node 0 to node 1 (but don't settle)
8357 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8359 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8360 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8361 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8362 let persister = test_utils::TestPersister::new();
8365 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8366 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8367 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8368 assert!(new_monitor == *monitor);
8371 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);
8372 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8375 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8376 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8377 // transaction lock time requirements here.
8378 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8379 watchtower.chain_monitor.block_connected(&block, 200);
8381 // Try to update ChannelMonitor
8382 nodes[1].node.claim_funds(preimage);
8383 check_added_monitors!(nodes[1], 1);
8384 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8386 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8387 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8388 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8390 let mut node_0_per_peer_lock;
8391 let mut node_0_peer_state_lock;
8392 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8393 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8394 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8395 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8396 } else { assert!(false); }
8398 // Our local monitor is in-sync and hasn't processed yet timeout
8399 check_added_monitors!(nodes[0], 1);
8400 let events = nodes[0].node.get_and_clear_pending_events();
8401 assert_eq!(events.len(), 1);
8405 fn test_concurrent_monitor_claim() {
8406 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8407 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8408 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8409 // state N+1 confirms. Alice claims output from state N+1.
8411 let chanmon_cfgs = create_chanmon_cfgs(2);
8412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8414 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8416 // Create some initial channel
8417 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8418 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8420 // Rebalance the network to generate htlc in the two directions
8421 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8423 // Route a HTLC from node 0 to node 1 (but don't settle)
8424 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8426 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8427 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8428 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8429 let persister = test_utils::TestPersister::new();
8430 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8431 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8433 let watchtower_alice = {
8435 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8436 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8437 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8438 assert!(new_monitor == *monitor);
8441 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8442 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8445 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8446 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8447 // requirements here.
8448 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8449 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8450 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8452 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8454 let mut txn = alice_broadcaster.txn_broadcast();
8455 assert_eq!(txn.len(), 2);
8459 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8460 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8461 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8462 let persister = test_utils::TestPersister::new();
8463 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8464 let watchtower_bob = {
8466 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8467 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8468 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8469 assert!(new_monitor == *monitor);
8472 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8473 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8476 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8478 // Route another payment to generate another update with still previous HTLC pending
8479 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8480 nodes[1].node.send_payment_with_route(&route, payment_hash,
8481 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8482 check_added_monitors!(nodes[1], 1);
8484 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8485 assert_eq!(updates.update_add_htlcs.len(), 1);
8486 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8488 let mut node_0_per_peer_lock;
8489 let mut node_0_peer_state_lock;
8490 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8491 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8492 // Watchtower Alice should already have seen the block and reject the update
8493 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8494 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8495 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8496 } else { assert!(false); }
8498 // Our local monitor is in-sync and hasn't processed yet timeout
8499 check_added_monitors!(nodes[0], 1);
8501 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8502 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8504 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8507 let mut txn = bob_broadcaster.txn_broadcast();
8508 assert_eq!(txn.len(), 2);
8509 bob_state_y = txn.remove(0);
8512 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8513 let height = HTLC_TIMEOUT_BROADCAST + 1;
8514 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8515 check_closed_broadcast(&nodes[0], 1, true);
8516 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8517 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8518 check_added_monitors(&nodes[0], 1);
8520 let htlc_txn = alice_broadcaster.txn_broadcast();
8521 assert_eq!(htlc_txn.len(), 2);
8522 check_spends!(htlc_txn[0], bob_state_y);
8523 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8524 // it. However, she should, because it now has an invalid parent.
8525 check_spends!(htlc_txn[1], alice_state);
8530 fn test_pre_lockin_no_chan_closed_update() {
8531 // Test that if a peer closes a channel in response to a funding_created message we don't
8532 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8535 // Doing so would imply a channel monitor update before the initial channel monitor
8536 // registration, violating our API guarantees.
8538 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8539 // then opening a second channel with the same funding output as the first (which is not
8540 // rejected because the first channel does not exist in the ChannelManager) and closing it
8541 // before receiving funding_signed.
8542 let chanmon_cfgs = create_chanmon_cfgs(2);
8543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8545 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8547 // Create an initial channel
8548 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8549 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8550 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8551 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8552 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8554 // Move the first channel through the funding flow...
8555 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8557 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8558 check_added_monitors!(nodes[0], 0);
8560 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8561 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8562 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8563 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8564 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8568 fn test_htlc_no_detection() {
8569 // This test is a mutation to underscore the detection logic bug we had
8570 // before #653. HTLC value routed is above the remaining balance, thus
8571 // inverting HTLC and `to_remote` output. HTLC will come second and
8572 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8573 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8574 // outputs order detection for correct spending children filtring.
8576 let chanmon_cfgs = create_chanmon_cfgs(2);
8577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8581 // Create some initial channels
8582 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8584 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8585 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8586 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8587 assert_eq!(local_txn[0].input.len(), 1);
8588 assert_eq!(local_txn[0].output.len(), 3);
8589 check_spends!(local_txn[0], chan_1.3);
8591 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8592 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8593 connect_block(&nodes[0], &block);
8594 // We deliberately connect the local tx twice as this should provoke a failure calling
8595 // this test before #653 fix.
8596 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8597 check_closed_broadcast!(nodes[0], true);
8598 check_added_monitors!(nodes[0], 1);
8599 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8600 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8602 let htlc_timeout = {
8603 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8604 assert_eq!(node_txn.len(), 1);
8605 assert_eq!(node_txn[0].input.len(), 1);
8606 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8607 check_spends!(node_txn[0], local_txn[0]);
8611 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8612 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8613 expect_payment_failed!(nodes[0], our_payment_hash, false);
8616 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8617 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8618 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8619 // Carol, Alice would be the upstream node, and Carol the downstream.)
8621 // Steps of the test:
8622 // 1) Alice sends a HTLC to Carol through Bob.
8623 // 2) Carol doesn't settle the HTLC.
8624 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8625 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8626 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8627 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8628 // 5) Carol release the preimage to Bob off-chain.
8629 // 6) Bob claims the offered output on the broadcasted commitment.
8630 let chanmon_cfgs = create_chanmon_cfgs(3);
8631 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8632 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8633 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8635 // Create some initial channels
8636 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8637 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8639 // Steps (1) and (2):
8640 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8641 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8643 // Check that Alice's commitment transaction now contains an output for this HTLC.
8644 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8645 check_spends!(alice_txn[0], chan_ab.3);
8646 assert_eq!(alice_txn[0].output.len(), 2);
8647 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8648 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8649 assert_eq!(alice_txn.len(), 2);
8651 // Steps (3) and (4):
8652 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8653 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8654 let mut force_closing_node = 0; // Alice force-closes
8655 let mut counterparty_node = 1; // Bob if Alice force-closes
8658 if !broadcast_alice {
8659 force_closing_node = 1;
8660 counterparty_node = 0;
8662 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8663 check_closed_broadcast!(nodes[force_closing_node], true);
8664 check_added_monitors!(nodes[force_closing_node], 1);
8665 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8666 if go_onchain_before_fulfill {
8667 let txn_to_broadcast = match broadcast_alice {
8668 true => alice_txn.clone(),
8669 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8671 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8672 if broadcast_alice {
8673 check_closed_broadcast!(nodes[1], true);
8674 check_added_monitors!(nodes[1], 1);
8675 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8680 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8681 // process of removing the HTLC from their commitment transactions.
8682 nodes[2].node.claim_funds(payment_preimage);
8683 check_added_monitors!(nodes[2], 1);
8684 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8686 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8687 assert!(carol_updates.update_add_htlcs.is_empty());
8688 assert!(carol_updates.update_fail_htlcs.is_empty());
8689 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8690 assert!(carol_updates.update_fee.is_none());
8691 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8693 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8694 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8695 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8696 if !go_onchain_before_fulfill && broadcast_alice {
8697 let events = nodes[1].node.get_and_clear_pending_msg_events();
8698 assert_eq!(events.len(), 1);
8700 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8701 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8703 _ => panic!("Unexpected event"),
8706 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8707 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8708 // Carol<->Bob's updated commitment transaction info.
8709 check_added_monitors!(nodes[1], 2);
8711 let events = nodes[1].node.get_and_clear_pending_msg_events();
8712 assert_eq!(events.len(), 2);
8713 let bob_revocation = match events[0] {
8714 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8715 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8718 _ => panic!("Unexpected event"),
8720 let bob_updates = match events[1] {
8721 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8722 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8725 _ => panic!("Unexpected event"),
8728 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8729 check_added_monitors!(nodes[2], 1);
8730 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8731 check_added_monitors!(nodes[2], 1);
8733 let events = nodes[2].node.get_and_clear_pending_msg_events();
8734 assert_eq!(events.len(), 1);
8735 let carol_revocation = match events[0] {
8736 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8737 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8740 _ => panic!("Unexpected event"),
8742 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8743 check_added_monitors!(nodes[1], 1);
8745 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8746 // here's where we put said channel's commitment tx on-chain.
8747 let mut txn_to_broadcast = alice_txn.clone();
8748 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8749 if !go_onchain_before_fulfill {
8750 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8751 // If Bob was the one to force-close, he will have already passed these checks earlier.
8752 if broadcast_alice {
8753 check_closed_broadcast!(nodes[1], true);
8754 check_added_monitors!(nodes[1], 1);
8755 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8757 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8758 if broadcast_alice {
8759 assert_eq!(bob_txn.len(), 1);
8760 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8762 assert_eq!(bob_txn.len(), 2);
8763 check_spends!(bob_txn[0], chan_ab.3);
8768 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8769 // broadcasted commitment transaction.
8771 let script_weight = match broadcast_alice {
8772 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8773 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8775 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8776 // Bob force-closed and broadcasts the commitment transaction along with a
8777 // HTLC-output-claiming transaction.
8778 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8779 if broadcast_alice {
8780 assert_eq!(bob_txn.len(), 1);
8781 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8782 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8784 assert_eq!(bob_txn.len(), 2);
8785 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8786 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8792 fn test_onchain_htlc_settlement_after_close() {
8793 do_test_onchain_htlc_settlement_after_close(true, true);
8794 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8795 do_test_onchain_htlc_settlement_after_close(true, false);
8796 do_test_onchain_htlc_settlement_after_close(false, false);
8800 fn test_duplicate_temporary_channel_id_from_different_peers() {
8801 // Tests that we can accept two different `OpenChannel` requests with the same
8802 // `temporary_channel_id`, as long as they are from different peers.
8803 let chanmon_cfgs = create_chanmon_cfgs(3);
8804 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8805 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8806 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8808 // Create an first channel channel
8809 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8810 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8812 // Create an second channel
8813 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8814 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8816 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8817 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8818 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8820 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8821 // `temporary_channel_id` as they are from different peers.
8822 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8824 let events = nodes[0].node.get_and_clear_pending_msg_events();
8825 assert_eq!(events.len(), 1);
8827 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8828 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8829 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8831 _ => panic!("Unexpected event"),
8835 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8837 let events = nodes[0].node.get_and_clear_pending_msg_events();
8838 assert_eq!(events.len(), 1);
8840 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8841 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8842 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8844 _ => panic!("Unexpected event"),
8850 fn test_duplicate_chan_id() {
8851 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8852 // already open we reject it and keep the old channel.
8854 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8855 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8856 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8857 // updating logic for the existing channel.
8858 let chanmon_cfgs = create_chanmon_cfgs(2);
8859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8863 // Create an initial channel
8864 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8865 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8866 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8867 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()));
8869 // Try to create a second channel with the same temporary_channel_id as the first and check
8870 // that it is rejected.
8871 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8873 let events = nodes[1].node.get_and_clear_pending_msg_events();
8874 assert_eq!(events.len(), 1);
8876 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8877 // Technically, at this point, nodes[1] would be justified in thinking both the
8878 // first (valid) and second (invalid) channels are closed, given they both have
8879 // the same non-temporary channel_id. However, currently we do not, so we just
8880 // move forward with it.
8881 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8882 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8884 _ => panic!("Unexpected event"),
8888 // Move the first channel through the funding flow...
8889 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8891 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8892 check_added_monitors!(nodes[0], 0);
8894 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8895 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8897 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8898 assert_eq!(added_monitors.len(), 1);
8899 assert_eq!(added_monitors[0].0, funding_output);
8900 added_monitors.clear();
8902 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8904 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8906 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8907 let channel_id = funding_outpoint.to_channel_id();
8909 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8912 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8913 // Technically this is allowed by the spec, but we don't support it and there's little reason
8914 // to. Still, it shouldn't cause any other issues.
8915 open_chan_msg.temporary_channel_id = channel_id;
8916 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8918 let events = nodes[1].node.get_and_clear_pending_msg_events();
8919 assert_eq!(events.len(), 1);
8921 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8922 // Technically, at this point, nodes[1] would be justified in thinking both
8923 // channels are closed, but currently we do not, so we just move forward with it.
8924 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8925 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8927 _ => panic!("Unexpected event"),
8931 // Now try to create a second channel which has a duplicate funding output.
8932 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8933 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8934 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8935 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()));
8936 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8938 let funding_created = {
8939 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8940 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8941 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8942 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8943 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8944 // channelmanager in a possibly nonsense state instead).
8945 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8946 let logger = test_utils::TestLogger::new();
8947 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8949 check_added_monitors!(nodes[0], 0);
8950 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8951 // At this point we'll look up if the channel_id is present and immediately fail the channel
8952 // without trying to persist the `ChannelMonitor`.
8953 check_added_monitors!(nodes[1], 0);
8955 // ...still, nodes[1] will reject the duplicate channel.
8957 let events = nodes[1].node.get_and_clear_pending_msg_events();
8958 assert_eq!(events.len(), 1);
8960 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8961 // Technically, at this point, nodes[1] would be justified in thinking both
8962 // channels are closed, but currently we do not, so we just move forward with it.
8963 assert_eq!(msg.channel_id, channel_id);
8964 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8966 _ => panic!("Unexpected event"),
8970 // finally, finish creating the original channel and send a payment over it to make sure
8971 // everything is functional.
8972 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8974 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8975 assert_eq!(added_monitors.len(), 1);
8976 assert_eq!(added_monitors[0].0, funding_output);
8977 added_monitors.clear();
8979 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8981 let events_4 = nodes[0].node.get_and_clear_pending_events();
8982 assert_eq!(events_4.len(), 0);
8983 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8984 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8986 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8987 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8988 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8990 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8994 fn test_error_chans_closed() {
8995 // Test that we properly handle error messages, closing appropriate channels.
8997 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8998 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8999 // we can test various edge cases around it to ensure we don't regress.
9000 let chanmon_cfgs = create_chanmon_cfgs(3);
9001 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9002 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9003 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9005 // Create some initial channels
9006 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9007 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9008 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9010 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9011 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9012 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9014 // Closing a channel from a different peer has no effect
9015 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9016 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9018 // Closing one channel doesn't impact others
9019 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9020 check_added_monitors!(nodes[0], 1);
9021 check_closed_broadcast!(nodes[0], false);
9022 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9023 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9024 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9025 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);
9026 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);
9028 // A null channel ID should close all channels
9029 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9030 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9031 check_added_monitors!(nodes[0], 2);
9032 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9033 let events = nodes[0].node.get_and_clear_pending_msg_events();
9034 assert_eq!(events.len(), 2);
9036 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9037 assert_eq!(msg.contents.flags & 2, 2);
9039 _ => panic!("Unexpected event"),
9042 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9043 assert_eq!(msg.contents.flags & 2, 2);
9045 _ => panic!("Unexpected event"),
9047 // Note that at this point users of a standard PeerHandler will end up calling
9048 // peer_disconnected.
9049 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9050 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9052 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9053 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9054 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9058 fn test_invalid_funding_tx() {
9059 // Test that we properly handle invalid funding transactions sent to us from a peer.
9061 // Previously, all other major lightning implementations had failed to properly sanitize
9062 // funding transactions from their counterparties, leading to a multi-implementation critical
9063 // security vulnerability (though we always sanitized properly, we've previously had
9064 // un-released crashes in the sanitization process).
9066 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9067 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9068 // gave up on it. We test this here by generating such a transaction.
9069 let chanmon_cfgs = create_chanmon_cfgs(2);
9070 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9071 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9072 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9074 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9075 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9076 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9078 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9080 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9081 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9082 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9084 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9085 let wit_program_script: Script = wit_program.into();
9086 for output in tx.output.iter_mut() {
9087 // Make the confirmed funding transaction have a bogus script_pubkey
9088 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9091 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9092 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9093 check_added_monitors!(nodes[1], 1);
9094 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9096 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9097 check_added_monitors!(nodes[0], 1);
9098 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9100 let events_1 = nodes[0].node.get_and_clear_pending_events();
9101 assert_eq!(events_1.len(), 0);
9103 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9104 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9105 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9107 let expected_err = "funding tx had wrong script/value or output index";
9108 confirm_transaction_at(&nodes[1], &tx, 1);
9109 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9110 check_added_monitors!(nodes[1], 1);
9111 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9112 assert_eq!(events_2.len(), 1);
9113 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9114 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9115 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9116 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9117 } else { panic!(); }
9118 } else { panic!(); }
9119 assert_eq!(nodes[1].node.list_channels().len(), 0);
9121 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9122 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9123 // as its not 32 bytes long.
9124 let mut spend_tx = Transaction {
9125 version: 2i32, lock_time: PackedLockTime::ZERO,
9126 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9127 previous_output: BitcoinOutPoint {
9131 script_sig: Script::new(),
9132 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9133 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9135 output: vec![TxOut {
9137 script_pubkey: Script::new(),
9140 check_spends!(spend_tx, tx);
9141 mine_transaction(&nodes[1], &spend_tx);
9144 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9145 // In the first version of the chain::Confirm interface, after a refactor was made to not
9146 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9147 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9148 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9149 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9150 // spending transaction until height N+1 (or greater). This was due to the way
9151 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9152 // spending transaction at the height the input transaction was confirmed at, not whether we
9153 // should broadcast a spending transaction at the current height.
9154 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9155 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9156 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9157 // until we learned about an additional block.
9159 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9160 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9161 let chanmon_cfgs = create_chanmon_cfgs(3);
9162 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9163 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9164 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9165 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9167 create_announced_chan_between_nodes(&nodes, 0, 1);
9168 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9169 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9170 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9171 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9173 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9174 check_closed_broadcast!(nodes[1], true);
9175 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9176 check_added_monitors!(nodes[1], 1);
9177 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9178 assert_eq!(node_txn.len(), 1);
9180 let conf_height = nodes[1].best_block_info().1;
9181 if !test_height_before_timelock {
9182 connect_blocks(&nodes[1], 24 * 6);
9184 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9185 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9186 if test_height_before_timelock {
9187 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9188 // generate any events or broadcast any transactions
9189 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9190 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9192 // We should broadcast an HTLC transaction spending our funding transaction first
9193 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9194 assert_eq!(spending_txn.len(), 2);
9195 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9196 check_spends!(spending_txn[1], node_txn[0]);
9197 // We should also generate a SpendableOutputs event with the to_self output (as its
9199 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9200 assert_eq!(descriptor_spend_txn.len(), 1);
9202 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9203 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9204 // additional block built on top of the current chain.
9205 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9206 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9207 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 }]);
9208 check_added_monitors!(nodes[1], 1);
9210 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9211 assert!(updates.update_add_htlcs.is_empty());
9212 assert!(updates.update_fulfill_htlcs.is_empty());
9213 assert_eq!(updates.update_fail_htlcs.len(), 1);
9214 assert!(updates.update_fail_malformed_htlcs.is_empty());
9215 assert!(updates.update_fee.is_none());
9216 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9217 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9218 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9223 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9224 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9225 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9228 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9229 let chanmon_cfgs = create_chanmon_cfgs(2);
9230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9232 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9234 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9236 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9237 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9238 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9240 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9243 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9244 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9245 check_added_monitors!(nodes[0], 1);
9246 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9247 assert_eq!(events.len(), 1);
9248 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9249 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9250 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9252 expect_pending_htlcs_forwardable!(nodes[1]);
9253 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9256 // Note that we use a different PaymentId here to allow us to duplicativly pay
9257 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9258 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9259 check_added_monitors!(nodes[0], 1);
9260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9261 assert_eq!(events.len(), 1);
9262 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9263 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9264 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9265 // At this point, nodes[1] would notice it has too much value for the payment. It will
9266 // assume the second is a privacy attack (no longer particularly relevant
9267 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9268 // the first HTLC delivered above.
9271 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9272 nodes[1].node.process_pending_htlc_forwards();
9274 if test_for_second_fail_panic {
9275 // Now we go fail back the first HTLC from the user end.
9276 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9278 let expected_destinations = vec![
9279 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9280 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9282 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9283 nodes[1].node.process_pending_htlc_forwards();
9285 check_added_monitors!(nodes[1], 1);
9286 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9287 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9289 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9290 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9291 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9293 let failure_events = nodes[0].node.get_and_clear_pending_events();
9294 assert_eq!(failure_events.len(), 4);
9295 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9296 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9297 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9298 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9300 // Let the second HTLC fail and claim the first
9301 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9302 nodes[1].node.process_pending_htlc_forwards();
9304 check_added_monitors!(nodes[1], 1);
9305 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9306 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9307 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9309 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9311 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9316 fn test_dup_htlc_second_fail_panic() {
9317 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9318 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9319 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9320 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9321 do_test_dup_htlc_second_rejected(true);
9325 fn test_dup_htlc_second_rejected() {
9326 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9327 // simply reject the second HTLC but are still able to claim the first HTLC.
9328 do_test_dup_htlc_second_rejected(false);
9332 fn test_inconsistent_mpp_params() {
9333 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9334 // such HTLC and allow the second to stay.
9335 let chanmon_cfgs = create_chanmon_cfgs(4);
9336 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9337 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9338 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9340 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9341 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9342 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9343 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9345 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9346 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9347 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9348 assert_eq!(route.paths.len(), 2);
9349 route.paths.sort_by(|path_a, _| {
9350 // Sort the path so that the path through nodes[1] comes first
9351 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9352 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9355 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9357 let cur_height = nodes[0].best_block_info().1;
9358 let payment_id = PaymentId([42; 32]);
9360 let session_privs = {
9361 // We create a fake route here so that we start with three pending HTLCs, which we'll
9362 // ultimately have, just not right away.
9363 let mut dup_route = route.clone();
9364 dup_route.paths.push(route.paths[1].clone());
9365 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9366 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9368 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9369 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9370 &None, session_privs[0]).unwrap();
9371 check_added_monitors!(nodes[0], 1);
9374 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9375 assert_eq!(events.len(), 1);
9376 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9378 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9380 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9381 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9382 check_added_monitors!(nodes[0], 1);
9385 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9386 assert_eq!(events.len(), 1);
9387 let payment_event = SendEvent::from_event(events.pop().unwrap());
9389 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9390 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9392 expect_pending_htlcs_forwardable!(nodes[2]);
9393 check_added_monitors!(nodes[2], 1);
9395 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9396 assert_eq!(events.len(), 1);
9397 let payment_event = SendEvent::from_event(events.pop().unwrap());
9399 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9400 check_added_monitors!(nodes[3], 0);
9401 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9403 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9404 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9405 // post-payment_secrets) and fail back the new HTLC.
9407 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9408 nodes[3].node.process_pending_htlc_forwards();
9409 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9410 nodes[3].node.process_pending_htlc_forwards();
9412 check_added_monitors!(nodes[3], 1);
9414 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9415 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9416 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9418 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 }]);
9419 check_added_monitors!(nodes[2], 1);
9421 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9422 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9423 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9425 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9427 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9428 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9429 &None, session_privs[2]).unwrap();
9430 check_added_monitors!(nodes[0], 1);
9432 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9433 assert_eq!(events.len(), 1);
9434 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9436 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9437 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9441 fn test_keysend_payments_to_public_node() {
9442 let chanmon_cfgs = create_chanmon_cfgs(2);
9443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9445 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9447 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9448 let network_graph = nodes[0].network_graph.clone();
9449 let payer_pubkey = nodes[0].node.get_our_node_id();
9450 let payee_pubkey = nodes[1].node.get_our_node_id();
9451 let route_params = RouteParameters {
9452 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9453 final_value_msat: 10000,
9455 let scorer = test_utils::TestScorer::new();
9456 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9457 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9459 let test_preimage = PaymentPreimage([42; 32]);
9460 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9461 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9462 check_added_monitors!(nodes[0], 1);
9463 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9464 assert_eq!(events.len(), 1);
9465 let event = events.pop().unwrap();
9466 let path = vec![&nodes[1]];
9467 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9468 claim_payment(&nodes[0], &path, test_preimage);
9472 fn test_keysend_payments_to_private_node() {
9473 let chanmon_cfgs = create_chanmon_cfgs(2);
9474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9476 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9478 let payer_pubkey = nodes[0].node.get_our_node_id();
9479 let payee_pubkey = nodes[1].node.get_our_node_id();
9481 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9482 let route_params = RouteParameters {
9483 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9484 final_value_msat: 10000,
9486 let network_graph = nodes[0].network_graph.clone();
9487 let first_hops = nodes[0].node.list_usable_channels();
9488 let scorer = test_utils::TestScorer::new();
9489 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9490 let route = find_route(
9491 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9492 nodes[0].logger, &scorer, &(), &random_seed_bytes
9495 let test_preimage = PaymentPreimage([42; 32]);
9496 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9497 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9498 check_added_monitors!(nodes[0], 1);
9499 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9500 assert_eq!(events.len(), 1);
9501 let event = events.pop().unwrap();
9502 let path = vec![&nodes[1]];
9503 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9504 claim_payment(&nodes[0], &path, test_preimage);
9508 fn test_double_partial_claim() {
9509 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9510 // time out, the sender resends only some of the MPP parts, then the user processes the
9511 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9513 let chanmon_cfgs = create_chanmon_cfgs(4);
9514 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9515 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9516 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9518 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9519 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9520 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9521 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9523 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9524 assert_eq!(route.paths.len(), 2);
9525 route.paths.sort_by(|path_a, _| {
9526 // Sort the path so that the path through nodes[1] comes first
9527 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9528 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9531 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9532 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9533 // amount of time to respond to.
9535 // Connect some blocks to time out the payment
9536 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9537 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9539 let failed_destinations = vec![
9540 HTLCDestination::FailedPayment { payment_hash },
9541 HTLCDestination::FailedPayment { payment_hash },
9543 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9545 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9547 // nodes[1] now retries one of the two paths...
9548 nodes[0].node.send_payment_with_route(&route, payment_hash,
9549 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9550 check_added_monitors!(nodes[0], 2);
9552 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9553 assert_eq!(events.len(), 2);
9554 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9555 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9557 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9558 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9559 nodes[3].node.claim_funds(payment_preimage);
9560 check_added_monitors!(nodes[3], 0);
9561 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9564 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9565 #[derive(Clone, Copy, PartialEq)]
9566 enum ExposureEvent {
9567 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9569 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9571 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9572 AtUpdateFeeOutbound,
9575 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9576 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9579 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9580 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9581 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9582 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9583 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9584 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9585 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9586 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9588 let chanmon_cfgs = create_chanmon_cfgs(2);
9589 let mut config = test_default_channel_config();
9590 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9593 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9595 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9596 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9597 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9598 open_channel.max_accepted_htlcs = 60;
9600 open_channel.dust_limit_satoshis = 546;
9602 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9603 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9604 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9606 let opt_anchors = false;
9608 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9611 let mut node_0_per_peer_lock;
9612 let mut node_0_peer_state_lock;
9613 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9614 chan.holder_dust_limit_satoshis = 546;
9617 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9618 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()));
9619 check_added_monitors!(nodes[1], 1);
9620 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9622 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()));
9623 check_added_monitors!(nodes[0], 1);
9624 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9626 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9627 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9628 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9630 let dust_buffer_feerate = {
9631 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9632 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9633 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9634 chan.get_dust_buffer_feerate(None) as u64
9636 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;
9637 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9639 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;
9640 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9642 let dust_htlc_on_counterparty_tx: u64 = 25;
9643 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9646 if dust_outbound_balance {
9647 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9648 // Outbound dust balance: 4372 sats
9649 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9650 for _ in 0..dust_outbound_htlc_on_holder_tx {
9651 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9652 nodes[0].node.send_payment_with_route(&route, payment_hash,
9653 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9656 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9657 // Inbound dust balance: 4372 sats
9658 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9659 for _ in 0..dust_inbound_htlc_on_holder_tx {
9660 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9664 if dust_outbound_balance {
9665 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9666 // Outbound dust balance: 5000 sats
9667 for _ in 0..dust_htlc_on_counterparty_tx {
9668 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9669 nodes[0].node.send_payment_with_route(&route, payment_hash,
9670 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9673 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9674 // Inbound dust balance: 5000 sats
9675 for _ in 0..dust_htlc_on_counterparty_tx {
9676 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9681 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9682 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9683 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 });
9684 let mut config = UserConfig::default();
9685 // With default dust exposure: 5000 sats
9687 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9688 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9689 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9690 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9691 ), true, APIError::ChannelUnavailable { ref err },
9692 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)));
9694 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9695 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9696 ), true, APIError::ChannelUnavailable { ref err },
9697 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)));
9699 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9700 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 });
9701 nodes[1].node.send_payment_with_route(&route, payment_hash,
9702 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9703 check_added_monitors!(nodes[1], 1);
9704 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9705 assert_eq!(events.len(), 1);
9706 let payment_event = SendEvent::from_event(events.remove(0));
9707 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9708 // With default dust exposure: 5000 sats
9710 // Outbound dust balance: 6399 sats
9711 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9712 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9713 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);
9715 // Outbound dust balance: 5200 sats
9716 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);
9718 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9719 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9720 nodes[0].node.send_payment_with_route(&route, payment_hash,
9721 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9723 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9724 *feerate_lock = *feerate_lock * 10;
9726 nodes[0].node.timer_tick_occurred();
9727 check_added_monitors!(nodes[0], 1);
9728 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9731 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9732 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9733 added_monitors.clear();
9737 fn test_max_dust_htlc_exposure() {
9738 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9739 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9740 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9741 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9742 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9743 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9744 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9745 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9746 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9747 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9748 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9749 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9753 fn test_non_final_funding_tx() {
9754 let chanmon_cfgs = create_chanmon_cfgs(2);
9755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9757 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9759 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9760 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9761 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9762 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9763 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9765 let best_height = nodes[0].node.best_block.read().unwrap().height();
9767 let chan_id = *nodes[0].network_chan_count.borrow();
9768 let events = nodes[0].node.get_and_clear_pending_events();
9769 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9770 assert_eq!(events.len(), 1);
9771 let mut tx = match events[0] {
9772 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9773 // Timelock the transaction _beyond_ the best client height + 1.
9774 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9775 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9778 _ => panic!("Unexpected event"),
9780 // Transaction should fail as it's evaluated as non-final for propagation.
9781 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9782 Err(APIError::APIMisuseError { err }) => {
9783 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9788 // However, transaction should be accepted if it's in a +1 headroom from best block.
9789 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9790 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9791 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9795 fn accept_busted_but_better_fee() {
9796 // If a peer sends us a fee update that is too low, but higher than our previous channel
9797 // feerate, we should accept it. In the future we may want to consider closing the channel
9798 // later, but for now we only accept the update.
9799 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9800 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9801 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9802 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9804 create_chan_between_nodes(&nodes[0], &nodes[1]);
9806 // Set nodes[1] to expect 5,000 sat/kW.
9808 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9809 *feerate_lock = 5000;
9812 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9814 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9815 *feerate_lock = 1000;
9817 nodes[0].node.timer_tick_occurred();
9818 check_added_monitors!(nodes[0], 1);
9820 let events = nodes[0].node.get_and_clear_pending_msg_events();
9821 assert_eq!(events.len(), 1);
9823 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9824 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9825 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9827 _ => panic!("Unexpected event"),
9830 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9833 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9834 *feerate_lock = 2000;
9836 nodes[0].node.timer_tick_occurred();
9837 check_added_monitors!(nodes[0], 1);
9839 let events = nodes[0].node.get_and_clear_pending_msg_events();
9840 assert_eq!(events.len(), 1);
9842 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9843 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9844 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9846 _ => panic!("Unexpected event"),
9849 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9852 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9853 *feerate_lock = 1000;
9855 nodes[0].node.timer_tick_occurred();
9856 check_added_monitors!(nodes[0], 1);
9858 let events = nodes[0].node.get_and_clear_pending_msg_events();
9859 assert_eq!(events.len(), 1);
9861 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9862 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9863 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9864 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9865 check_closed_broadcast!(nodes[1], true);
9866 check_added_monitors!(nodes[1], 1);
9868 _ => panic!("Unexpected event"),
9872 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9873 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9874 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9875 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9876 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9877 let min_final_cltv_expiry_delta = 120;
9878 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9879 min_final_cltv_expiry_delta - 2 };
9880 let recv_value = 100_000;
9882 create_chan_between_nodes(&nodes[0], &nodes[1]);
9884 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9885 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9886 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9887 Some(recv_value), Some(min_final_cltv_expiry_delta));
9888 (payment_hash, payment_preimage, payment_secret)
9890 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9891 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9893 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9894 nodes[0].node.send_payment_with_route(&route, payment_hash,
9895 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9896 check_added_monitors!(nodes[0], 1);
9897 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9898 assert_eq!(events.len(), 1);
9899 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9900 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9901 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9902 expect_pending_htlcs_forwardable!(nodes[1]);
9905 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9906 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9908 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9910 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9912 check_added_monitors!(nodes[1], 1);
9914 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9915 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9916 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9918 expect_payment_failed!(nodes[0], payment_hash, true);
9923 fn test_payment_with_custom_min_cltv_expiry_delta() {
9924 do_payment_with_custom_min_final_cltv_expiry(false, false);
9925 do_payment_with_custom_min_final_cltv_expiry(false, true);
9926 do_payment_with_custom_min_final_cltv_expiry(true, false);
9927 do_payment_with_custom_min_final_cltv_expiry(true, true);