1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, RouteParameters, find_route, get_route};
30 use crate::ln::features::{ChannelFeatures, NodeFeatures};
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::enforcing_trait_impls::EnforcingSigner;
34 use crate::util::test_utils;
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::UserConfig;
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
108 insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
118 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None).unwrap();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183 chan.holder_selected_channel_reserve_satoshis = 0;
184 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193 if send_from_initiator {
194 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195 // Note that for outbound channels we have to consider the commitment tx fee and the
196 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197 // well as an additional HTLC.
198 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200 send_payment(&nodes[1], &[&nodes[0]], push_amt);
205 fn test_counterparty_no_reserve() {
206 do_test_counterparty_no_reserve(true);
207 do_test_counterparty_no_reserve(false);
211 fn test_async_inbound_update_fee() {
212 let chanmon_cfgs = create_chanmon_cfgs(2);
213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216 create_announced_chan_between_nodes(&nodes, 0, 1);
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
223 // send (1) commitment_signed -.
224 // <- update_add_htlc/commitment_signed
225 // send (2) RAA (awaiting remote revoke) -.
226 // (1) commitment_signed is delivered ->
227 // .- send (3) RAA (awaiting remote revoke)
228 // (2) RAA is delivered ->
229 // .- send (4) commitment_signed
230 // <- (3) RAA is delivered
231 // send (5) commitment_signed -.
232 // <- (4) commitment_signed is delivered
234 // (5) commitment_signed is delivered ->
236 // (6) RAA is delivered ->
238 // First nodes[0] generates an update_fee
240 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
243 nodes[0].node.timer_tick_occurred();
244 check_added_monitors!(nodes[0], 1);
246 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247 assert_eq!(events_0.len(), 1);
248 let (update_msg, commitment_signed) = match events_0[0] { // (1)
249 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250 (update_fee.as_ref(), commitment_signed)
252 _ => panic!("Unexpected event"),
255 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261 check_added_monitors!(nodes[1], 1);
263 let payment_event = {
264 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265 assert_eq!(events_1.len(), 1);
266 SendEvent::from_event(events_1.remove(0))
268 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269 assert_eq!(payment_event.msgs.len(), 1);
271 // ...now when the messages get delivered everyone should be happy
272 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276 check_added_monitors!(nodes[0], 1);
278 // deliver(1), generate (3):
279 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[1], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290 assert!(bs_update.update_fee.is_none()); // (4)
291 check_added_monitors!(nodes[1], 1);
293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295 assert!(as_update.update_add_htlcs.is_empty()); // (5)
296 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299 assert!(as_update.update_fee.is_none()); // (5)
300 check_added_monitors!(nodes[0], 1);
302 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304 // only (6) so get_event_msg's assert(len == 1) passes
305 check_added_monitors!(nodes[0], 1);
307 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309 check_added_monitors!(nodes[1], 1);
311 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312 check_added_monitors!(nodes[0], 1);
314 let events_2 = nodes[0].node.get_and_clear_pending_events();
315 assert_eq!(events_2.len(), 1);
317 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318 _ => panic!("Unexpected event"),
321 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322 check_added_monitors!(nodes[1], 1);
326 fn test_update_fee_unordered_raa() {
327 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328 // crash in an earlier version of the update_fee patch)
329 let chanmon_cfgs = create_chanmon_cfgs(2);
330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333 create_announced_chan_between_nodes(&nodes, 0, 1);
336 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
338 // First nodes[0] generates an update_fee
340 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
343 nodes[0].node.timer_tick_occurred();
344 check_added_monitors!(nodes[0], 1);
346 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347 assert_eq!(events_0.len(), 1);
348 let update_msg = match events_0[0] { // (1)
349 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
352 _ => panic!("Unexpected event"),
355 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
357 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361 check_added_monitors!(nodes[1], 1);
363 let payment_event = {
364 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365 assert_eq!(events_1.len(), 1);
366 SendEvent::from_event(events_1.remove(0))
368 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369 assert_eq!(payment_event.msgs.len(), 1);
371 // ...now when the messages get delivered everyone should be happy
372 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376 check_added_monitors!(nodes[0], 1);
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379 check_added_monitors!(nodes[1], 1);
381 // We can't continue, sadly, because our (1) now has a bogus signature
385 fn test_multi_flight_update_fee() {
386 let chanmon_cfgs = create_chanmon_cfgs(2);
387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390 create_announced_chan_between_nodes(&nodes, 0, 1);
393 // update_fee/commitment_signed ->
394 // .- send (1) RAA and (2) commitment_signed
395 // update_fee (never committed) ->
397 // We have to manually generate the above update_fee, it is allowed by the protocol but we
398 // don't track which updates correspond to which revoke_and_ack responses so we're in
399 // AwaitingRAA mode and will not generate the update_fee yet.
400 // <- (1) RAA delivered
401 // (3) is generated and send (4) CS -.
402 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403 // know the per_commitment_point to use for it.
404 // <- (2) commitment_signed delivered
406 // B should send no response here
407 // (4) commitment_signed delivered ->
408 // <- RAA/commitment_signed delivered
411 // First nodes[0] generates an update_fee
414 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415 initial_feerate = *feerate_lock;
416 *feerate_lock = initial_feerate + 20;
418 nodes[0].node.timer_tick_occurred();
419 check_added_monitors!(nodes[0], 1);
421 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422 assert_eq!(events_0.len(), 1);
423 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425 (update_fee.as_ref().unwrap(), commitment_signed)
427 _ => panic!("Unexpected event"),
430 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434 check_added_monitors!(nodes[1], 1);
436 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
439 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440 *feerate_lock = initial_feerate + 40;
442 nodes[0].node.timer_tick_occurred();
443 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
446 // Create the (3) update_fee message that nodes[0] will generate before it does...
447 let mut update_msg_2 = msgs::UpdateFee {
448 channel_id: update_msg_1.channel_id.clone(),
449 feerate_per_kw: (initial_feerate + 30) as u32,
452 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
454 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
456 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
458 // Deliver (1), generating (3) and (4)
459 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 assert!(as_second_update.update_add_htlcs.is_empty());
463 assert!(as_second_update.update_fulfill_htlcs.is_empty());
464 assert!(as_second_update.update_fail_htlcs.is_empty());
465 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466 // Check that the update_fee newly generated matches what we delivered:
467 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
470 // Deliver (2) commitment_signed
471 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473 check_added_monitors!(nodes[0], 1);
474 // No commitment_signed so get_event_msg's assert(len == 1) passes
476 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[1], 1);
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[0], 1);
489 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491 // No commitment_signed so get_event_msg's assert(len == 1) passes
492 check_added_monitors!(nodes[0], 1);
494 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496 check_added_monitors!(nodes[1], 1);
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500 // Previously, we had issues deserializing channels when we hadn't connected the first block
501 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502 // serialization round-trips and simply do steps towards opening a channel and then drop the
505 let chanmon_cfgs = create_chanmon_cfgs(2);
506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
510 if steps & 0b1000_0000 != 0{
511 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512 connect_block(&nodes[0], &block);
513 connect_block(&nodes[1], &block);
516 if steps & 0x0f == 0 { return; }
517 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520 if steps & 0x0f == 1 { return; }
521 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524 if steps & 0x0f == 2 { return; }
525 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
527 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529 if steps & 0x0f == 3 { return; }
530 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531 check_added_monitors!(nodes[0], 0);
532 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534 if steps & 0x0f == 4 { return; }
535 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538 assert_eq!(added_monitors.len(), 1);
539 assert_eq!(added_monitors[0].0, funding_output);
540 added_monitors.clear();
542 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
544 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
546 if steps & 0x0f == 5 { return; }
547 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
549 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550 assert_eq!(added_monitors.len(), 1);
551 assert_eq!(added_monitors[0].0, funding_output);
552 added_monitors.clear();
555 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556 let events_4 = nodes[0].node.get_and_clear_pending_events();
557 assert_eq!(events_4.len(), 0);
559 if steps & 0x0f == 6 { return; }
560 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
562 if steps & 0x0f == 7 { return; }
563 confirm_transaction_at(&nodes[0], &tx, 2);
564 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
570 fn test_sanity_on_in_flight_opens() {
571 do_test_sanity_on_in_flight_opens(0);
572 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(1);
574 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(2);
576 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(3);
578 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(4);
580 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(5);
582 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(6);
584 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(7);
586 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(8);
588 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
592 fn test_update_fee_vanilla() {
593 let chanmon_cfgs = create_chanmon_cfgs(2);
594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597 create_announced_chan_between_nodes(&nodes, 0, 1);
600 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603 nodes[0].node.timer_tick_occurred();
604 check_added_monitors!(nodes[0], 1);
606 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607 assert_eq!(events_0.len(), 1);
608 let (update_msg, commitment_signed) = match events_0[0] {
609 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
610 (update_fee.as_ref(), commitment_signed)
612 _ => panic!("Unexpected event"),
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
616 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618 check_added_monitors!(nodes[1], 1);
620 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622 check_added_monitors!(nodes[0], 1);
624 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626 // No commitment_signed so get_event_msg's assert(len == 1) passes
627 check_added_monitors!(nodes[0], 1);
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631 check_added_monitors!(nodes[1], 1);
635 fn test_update_fee_that_funder_cannot_afford() {
636 let chanmon_cfgs = create_chanmon_cfgs(2);
637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640 let channel_value = 5000;
642 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643 let channel_id = chan.2;
644 let secp_ctx = Secp256k1::new();
645 let default_config = UserConfig::default();
646 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
648 let opt_anchors = false;
650 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652 // calculate two different feerates here - the expected local limit as well as the expected
654 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(opt_anchors) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
655 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658 *feerate_lock = feerate;
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
662 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
666 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
668 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
670 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
672 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673 assert_eq!(commitment_tx.output.len(), 2);
674 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676 actual_fee = channel_value - actual_fee;
677 assert_eq!(total_fee, actual_fee);
681 // Increment the feerate by a small constant, accounting for rounding errors
682 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685 nodes[0].node.timer_tick_occurred();
686 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687 check_added_monitors!(nodes[0], 0);
689 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
691 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692 // needed to sign the new commitment tx and (2) sign the new commitment tx.
693 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697 let chan_signer = local_chan.get_signer();
698 let pubkeys = chan_signer.pubkeys();
699 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700 pubkeys.funding_pubkey)
702 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706 let chan_signer = remote_chan.get_signer();
707 let pubkeys = chan_signer.pubkeys();
708 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710 pubkeys.funding_pubkey)
713 // Assemble the set of keys we can use for signatures for our commitment_signed message.
714 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
718 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721 let local_chan_signer = local_chan.get_signer();
722 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724 INITIAL_COMMITMENT_NUMBER - 1,
726 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727 opt_anchors, local_funding, remote_funding,
728 commit_tx_keys.clone(),
729 non_buffer_feerate + 4,
731 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
733 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736 let commit_signed_msg = msgs::CommitmentSigned {
739 htlc_signatures: res.1,
741 partial_signature_with_nonce: None,
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
798 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799 assert_eq!(added_monitors.len(), 0);
800 added_monitors.clear();
802 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 // node[1] has nothing to do
806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 check_added_monitors!(nodes[0], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 check_added_monitors!(nodes[0], 1);
814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815 check_added_monitors!(nodes[1], 1);
816 // AwaitingRemoteRevoke ends here
818 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fee.is_none(), true);
825 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827 check_added_monitors!(nodes[0], 1);
828 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831 check_added_monitors!(nodes[1], 1);
832 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835 check_added_monitors!(nodes[1], 1);
836 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837 // No commitment_signed so get_event_msg's assert(len == 1) passes
839 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[0], 1);
841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
843 expect_pending_htlcs_forwardable!(nodes[0]);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentClaimable { .. } => { },
849 _ => panic!("Unexpected event"),
852 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
854 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
862 fn test_update_fee() {
863 let chanmon_cfgs = create_chanmon_cfgs(2);
864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868 let channel_id = chan.2;
871 // (1) update_fee/commitment_signed ->
872 // <- (2) revoke_and_ack
873 // .- send (3) commitment_signed
874 // (4) update_fee/commitment_signed ->
875 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876 // <- (3) commitment_signed delivered
877 // send (6) revoke_and_ack -.
878 // <- (5) deliver revoke_and_ack
879 // (6) deliver revoke_and_ack ->
880 // .- send (7) commitment_signed in response to (4)
881 // <- (7) deliver commitment_signed
884 // Create and deliver (1)...
887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888 feerate = *feerate_lock;
889 *feerate_lock = feerate + 20;
891 nodes[0].node.timer_tick_occurred();
892 check_added_monitors!(nodes[0], 1);
894 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895 assert_eq!(events_0.len(), 1);
896 let (update_msg, commitment_signed) = match events_0[0] {
897 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
898 (update_fee.as_ref(), commitment_signed)
900 _ => panic!("Unexpected event"),
902 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
904 // Generate (2) and (3):
905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912 check_added_monitors!(nodes[0], 1);
914 // Create and deliver (4)...
916 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917 *feerate_lock = feerate + 30;
919 nodes[0].node.timer_tick_occurred();
920 check_added_monitors!(nodes[0], 1);
921 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922 assert_eq!(events_0.len(), 1);
923 let (update_msg, commitment_signed) = match events_0[0] {
924 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
925 (update_fee.as_ref(), commitment_signed)
927 _ => panic!("Unexpected event"),
930 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932 check_added_monitors!(nodes[1], 1);
934 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
937 // Handle (3), creating (6):
938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939 check_added_monitors!(nodes[0], 1);
940 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 check_added_monitors!(nodes[0], 1);
948 // Deliver (6), creating (7):
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951 assert!(commitment_update.update_add_htlcs.is_empty());
952 assert!(commitment_update.update_fulfill_htlcs.is_empty());
953 assert!(commitment_update.update_fail_htlcs.is_empty());
954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955 assert!(commitment_update.update_fee.is_none());
956 check_added_monitors!(nodes[1], 1);
959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960 check_added_monitors!(nodes[0], 1);
961 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962 // No commitment_signed so get_event_msg's assert(len == 1) passes
964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965 check_added_monitors!(nodes[1], 1);
966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
968 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
976 fn fake_network_test() {
977 // Simple test which builds a network of ChannelManagers, connects them to each other, and
978 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979 let chanmon_cfgs = create_chanmon_cfgs(4);
980 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
984 // Create some initial channels
985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
989 // Rebalance the network a bit by relaying one payment through all the channels...
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 // Send some more payments
996 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1000 // Test failure packets
1001 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1004 // Add a new channel that skips 3
1005 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 // Do some rebalance loop payments, simultaneously
1016 let mut hops = Vec::with_capacity(3);
1017 hops.push(RouteHop {
1018 pubkey: nodes[2].node.get_our_node_id(),
1019 node_features: NodeFeatures::empty(),
1020 short_channel_id: chan_2.0.contents.short_channel_id,
1021 channel_features: ChannelFeatures::empty(),
1023 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1025 hops.push(RouteHop {
1026 pubkey: nodes[3].node.get_our_node_id(),
1027 node_features: NodeFeatures::empty(),
1028 short_channel_id: chan_3.0.contents.short_channel_id,
1029 channel_features: ChannelFeatures::empty(),
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 node_features: nodes[1].node.node_features(),
1036 short_channel_id: chan_4.0.contents.short_channel_id,
1037 channel_features: nodes[1].node.channel_features(),
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1042 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1043 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 node_features: NodeFeatures::empty(),
1049 short_channel_id: chan_4.0.contents.short_channel_id,
1050 channel_features: ChannelFeatures::empty(),
1052 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1054 hops.push(RouteHop {
1055 pubkey: nodes[2].node.get_our_node_id(),
1056 node_features: NodeFeatures::empty(),
1057 short_channel_id: chan_3.0.contents.short_channel_id,
1058 channel_features: ChannelFeatures::empty(),
1060 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1062 hops.push(RouteHop {
1063 pubkey: nodes[1].node.get_our_node_id(),
1064 node_features: nodes[1].node.node_features(),
1065 short_channel_id: chan_2.0.contents.short_channel_id,
1066 channel_features: nodes[1].node.channel_features(),
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1071 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1072 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 fn holding_cell_htlc_counting() {
1095 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097 // commitment dance rounds.
1098 let chanmon_cfgs = create_chanmon_cfgs(3);
1099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1105 let mut payments = Vec::new();
1107 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 nodes[1].node.send_payment_with_route(&route, payment_hash,
1109 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1110 payments.push((payment_preimage, payment_hash));
1112 check_added_monitors!(nodes[1], 1);
1114 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115 assert_eq!(events.len(), 1);
1116 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1119 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1122 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1124 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1125 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1126 ), true, APIError::ChannelUnavailable { ref err },
1127 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1128 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141 assert_eq!(events.len(), 1);
1142 let payment_event = SendEvent::from_event(events.pop().unwrap());
1143 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148 // fails), the second will process the resulting failure and fail the HTLC backward.
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1151 check_added_monitors!(nodes[1], 1);
1153 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1157 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1159 // Now forward all the pending HTLCs and claim them back
1160 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 for ref update in as_updates.update_add_htlcs.iter() {
1174 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1176 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177 check_added_monitors!(nodes[2], 1);
1178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179 check_added_monitors!(nodes[2], 1);
1180 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183 check_added_monitors!(nodes[1], 1);
1184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185 check_added_monitors!(nodes[1], 1);
1186 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1188 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189 check_added_monitors!(nodes[2], 1);
1191 expect_pending_htlcs_forwardable!(nodes[2]);
1193 let events = nodes[2].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), payments.len());
1195 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1197 &Event::PaymentClaimable { ref payment_hash, .. } => {
1198 assert_eq!(*payment_hash, *hash);
1200 _ => panic!("Unexpected event"),
1204 for (preimage, _) in payments.drain(..) {
1205 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 fn duplicate_htlc_test() {
1213 // Test that we accept duplicate payment_hash HTLCs across the network and that
1214 // claiming/failing them are all separate and don't affect each other
1215 let chanmon_cfgs = create_chanmon_cfgs(6);
1216 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1220 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221 create_announced_chan_between_nodes(&nodes, 0, 3);
1222 create_announced_chan_between_nodes(&nodes, 1, 3);
1223 create_announced_chan_between_nodes(&nodes, 2, 3);
1224 create_announced_chan_between_nodes(&nodes, 3, 4);
1225 create_announced_chan_between_nodes(&nodes, 3, 5);
1227 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1232 *nodes[0].network_payment_count.borrow_mut() -= 1;
1233 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1235 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242 // Test that ChannelMonitor doesn't generate 2 preimage txn
1243 // when we have 2 HTLCs with same preimage that go across a node
1244 // in opposite directions, even with the same payment secret.
1245 let chanmon_cfgs = create_chanmon_cfgs(2);
1246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1255 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1257 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1261 // Provide preimage to node 0 by claiming payment
1262 nodes[0].node.claim_funds(payment_preimage);
1263 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264 check_added_monitors!(nodes[0], 1);
1266 // Broadcast node 1 commitment txn
1267 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1269 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270 let mut has_both_htlcs = 0; // check htlcs match ones committed
1271 for outp in remote_txn[0].output.iter() {
1272 if outp.value == 800_000 / 1000 {
1273 has_both_htlcs += 1;
1274 } else if outp.value == 900_000 / 1000 {
1275 has_both_htlcs += 1;
1278 assert_eq!(has_both_htlcs, 2);
1280 mine_transaction(&nodes[0], &remote_txn[0]);
1281 check_added_monitors!(nodes[0], 1);
1282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 3);
1288 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289 check_spends!(claim_txn[1], remote_txn[0]);
1290 check_spends!(claim_txn[2], remote_txn[0]);
1291 let preimage_tx = &claim_txn[0];
1292 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293 (&claim_txn[1], &claim_txn[2])
1295 (&claim_txn[2], &claim_txn[1])
1298 assert_eq!(preimage_tx.input.len(), 1);
1299 assert_eq!(preimage_bump_tx.input.len(), 1);
1301 assert_eq!(preimage_tx.input.len(), 1);
1302 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1305 assert_eq!(timeout_tx.input.len(), 1);
1306 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307 check_spends!(timeout_tx, remote_txn[0]);
1308 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1310 let events = nodes[0].node.get_and_clear_pending_msg_events();
1311 assert_eq!(events.len(), 3);
1314 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1319 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1320 assert!(update_add_htlcs.is_empty());
1321 assert!(update_fail_htlcs.is_empty());
1322 assert_eq!(update_fulfill_htlcs.len(), 1);
1323 assert!(update_fail_malformed_htlcs.is_empty());
1324 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1326 _ => panic!("Unexpected event"),
1332 fn test_basic_channel_reserve() {
1333 let chanmon_cfgs = create_chanmon_cfgs(2);
1334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1339 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340 let channel_reserve = chan_stat.channel_reserve_msat;
1342 // The 2* and +1 are for the fee spike reserve.
1343 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1344 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1346 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1347 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1349 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1351 &APIError::ChannelUnavailable{ref err} =>
1352 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1353 _ => panic!("Unexpected error variant"),
1356 _ => panic!("Unexpected error variant"),
1358 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1359 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1361 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1365 fn test_fee_spike_violation_fails_htlc() {
1366 let chanmon_cfgs = create_chanmon_cfgs(2);
1367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1370 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1372 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1373 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1374 let secp_ctx = Secp256k1::new();
1375 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1377 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1379 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1380 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1381 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1382 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1383 let msg = msgs::UpdateAddHTLC {
1386 amount_msat: htlc_msat,
1387 payment_hash: payment_hash,
1388 cltv_expiry: htlc_cltv,
1389 onion_routing_packet: onion_packet,
1392 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1394 // Now manually create the commitment_signed message corresponding to the update_add
1395 // nodes[0] just sent. In the code for construction of this message, "local" refers
1396 // to the sender of the message, and "remote" refers to the receiver.
1398 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1400 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1402 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1403 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1404 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1405 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1406 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1407 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1408 let chan_signer = local_chan.get_signer();
1409 // Make the signer believe we validated another commitment, so we can release the secret
1410 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1412 let pubkeys = chan_signer.pubkeys();
1413 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1414 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1415 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1416 chan_signer.pubkeys().funding_pubkey)
1418 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1419 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1420 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1421 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422 let chan_signer = remote_chan.get_signer();
1423 let pubkeys = chan_signer.pubkeys();
1424 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1425 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1426 chan_signer.pubkeys().funding_pubkey)
1429 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1430 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1431 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1433 // Build the remote commitment transaction so we can sign it, and then later use the
1434 // signature for the commitment_signed message.
1435 let local_chan_balance = 1313;
1437 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1439 amount_msat: 3460001,
1440 cltv_expiry: htlc_cltv,
1442 transaction_output_index: Some(1),
1445 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1448 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1449 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1450 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1451 let local_chan_signer = local_chan.get_signer();
1452 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1456 local_chan.opt_anchors(), local_funding, remote_funding,
1457 commit_tx_keys.clone(),
1459 &mut vec![(accepted_htlc_info, ())],
1460 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1462 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1465 let commit_signed_msg = msgs::CommitmentSigned {
1468 htlc_signatures: res.1,
1470 partial_signature_with_nonce: None,
1473 // Send the commitment_signed message to the nodes[1].
1474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1477 // Send the RAA to nodes[1].
1478 let raa_msg = msgs::RevokeAndACK {
1480 per_commitment_secret: local_secret,
1481 next_per_commitment_point: next_local_point,
1483 next_local_nonce: None,
1485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1487 let events = nodes[1].node.get_and_clear_pending_msg_events();
1488 assert_eq!(events.len(), 1);
1489 // Make sure the HTLC failed in the way we expect.
1491 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492 assert_eq!(update_fail_htlcs.len(), 1);
1493 update_fail_htlcs[0].clone()
1495 _ => panic!("Unexpected event"),
1497 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1500 check_added_monitors!(nodes[1], 2);
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506 // Set the fee rate for the channel very high, to the point where the fundee
1507 // sending any above-dust amount would result in a channel reserve violation.
1508 // In this test we check that we would be prevented from sending an HTLC in
1510 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514 let default_config = UserConfig::default();
1515 let opt_anchors = false;
1517 let mut push_amt = 100_000_000;
1518 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1520 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1522 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1524 // Sending exactly enough to hit the reserve amount should be accepted
1525 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1526 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1529 // However one more HTLC should be significantly over the reserve amount and fail.
1530 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1531 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1532 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1533 ), true, APIError::ChannelUnavailable { ref err },
1534 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1535 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1536 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1540 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1541 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1542 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1545 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1546 let default_config = UserConfig::default();
1547 let opt_anchors = false;
1549 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1550 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1551 // transaction fee with 0 HTLCs (183 sats)).
1552 let mut push_amt = 100_000_000;
1553 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1554 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1555 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1557 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1558 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1559 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1562 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1563 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1564 let secp_ctx = Secp256k1::new();
1565 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1566 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1567 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1568 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1569 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1570 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1571 let msg = msgs::UpdateAddHTLC {
1573 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1574 amount_msat: htlc_msat,
1575 payment_hash: payment_hash,
1576 cltv_expiry: htlc_cltv,
1577 onion_routing_packet: onion_packet,
1580 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1581 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1582 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1583 assert_eq!(nodes[0].node.list_channels().len(), 0);
1584 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1585 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1586 check_added_monitors!(nodes[0], 1);
1587 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1591 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1592 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1593 // calculating our commitment transaction fee (this was previously broken).
1594 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1595 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1599 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1600 let default_config = UserConfig::default();
1601 let opt_anchors = false;
1603 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1604 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1605 // transaction fee with 0 HTLCs (183 sats)).
1606 let mut push_amt = 100_000_000;
1607 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1608 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1609 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1611 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1612 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1613 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1614 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1615 // commitment transaction fee.
1616 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1618 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1619 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1623 // One more than the dust amt should fail, however.
1624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1625 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1626 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1627 ), true, APIError::ChannelUnavailable { ref err },
1628 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1632 fn test_chan_init_feerate_unaffordability() {
1633 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1634 // channel reserve and feerate requirements.
1635 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1636 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1640 let default_config = UserConfig::default();
1641 let opt_anchors = false;
1643 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1645 let mut push_amt = 100_000_000;
1646 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1647 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1648 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1650 // During open, we don't have a "counterparty channel reserve" to check against, so that
1651 // requirement only comes into play on the open_channel handling side.
1652 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1653 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1654 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1655 open_channel_msg.push_msat += 1;
1656 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1658 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1659 assert_eq!(msg_events.len(), 1);
1660 match msg_events[0] {
1661 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1662 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1664 _ => panic!("Unexpected event"),
1669 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1670 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1671 // calculating our counterparty's commitment transaction fee (this was previously broken).
1672 let chanmon_cfgs = create_chanmon_cfgs(2);
1673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1676 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1678 let payment_amt = 46000; // Dust amount
1679 // In the previous code, these first four payments would succeed.
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1693 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1694 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1695 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1700 let chanmon_cfgs = create_chanmon_cfgs(3);
1701 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1702 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1703 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1704 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1705 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1708 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1709 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1710 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1711 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1713 // Add a 2* and +1 for the fee spike reserve.
1714 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1715 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1716 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1718 // Add a pending HTLC.
1719 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1720 let payment_event_1 = {
1721 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1722 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1723 check_added_monitors!(nodes[0], 1);
1725 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1726 assert_eq!(events.len(), 1);
1727 SendEvent::from_event(events.remove(0))
1729 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1731 // Attempt to trigger a channel reserve violation --> payment failure.
1732 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1733 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1734 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1735 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1737 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1738 let secp_ctx = Secp256k1::new();
1739 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1740 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1741 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1742 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1743 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1744 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1745 let msg = msgs::UpdateAddHTLC {
1748 amount_msat: htlc_msat + 1,
1749 payment_hash: our_payment_hash_1,
1750 cltv_expiry: htlc_cltv,
1751 onion_routing_packet: onion_packet,
1754 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1755 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1756 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1757 assert_eq!(nodes[1].node.list_channels().len(), 1);
1758 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1759 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1760 check_added_monitors!(nodes[1], 1);
1761 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1765 fn test_inbound_outbound_capacity_is_not_zero() {
1766 let chanmon_cfgs = create_chanmon_cfgs(2);
1767 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1768 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1769 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1770 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1771 let channels0 = node_chanmgrs[0].list_channels();
1772 let channels1 = node_chanmgrs[1].list_channels();
1773 let default_config = UserConfig::default();
1774 assert_eq!(channels0.len(), 1);
1775 assert_eq!(channels1.len(), 1);
1777 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1778 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1779 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1781 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1782 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1785 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1786 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1790 fn test_channel_reserve_holding_cell_htlcs() {
1791 let chanmon_cfgs = create_chanmon_cfgs(3);
1792 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1793 // When this test was written, the default base fee floated based on the HTLC count.
1794 // It is now fixed, so we simply set the fee to the expected value here.
1795 let mut config = test_default_channel_config();
1796 config.channel_config.forwarding_fee_base_msat = 239;
1797 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1798 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1799 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1800 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1802 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1803 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1805 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1806 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1808 macro_rules! expect_forward {
1810 let mut events = $node.node.get_and_clear_pending_msg_events();
1811 assert_eq!(events.len(), 1);
1812 check_added_monitors!($node, 1);
1813 let payment_event = SendEvent::from_event(events.remove(0));
1818 let feemsat = 239; // set above
1819 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1820 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1821 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1823 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1825 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1827 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1828 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1829 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1830 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1831 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1833 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1834 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1835 ), true, APIError::ChannelUnavailable { ref err },
1836 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1837 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1838 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1841 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1842 // nodes[0]'s wealth
1844 let amt_msat = recv_value_0 + total_fee_msat;
1845 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1846 // Also, ensure that each payment has enough to be over the dust limit to
1847 // ensure it'll be included in each commit tx fee calculation.
1848 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1849 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1850 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1854 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1855 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1856 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1857 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1858 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1860 let (stat01_, stat11_, stat12_, stat22_) = (
1861 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1862 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1863 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1864 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1867 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1868 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1869 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1870 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1871 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1874 // adding pending output.
1875 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1876 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1877 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1878 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1879 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1880 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1881 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1882 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1883 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1885 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1886 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1887 let amt_msat_1 = recv_value_1 + total_fee_msat;
1889 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1890 let payment_event_1 = {
1891 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1892 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1893 check_added_monitors!(nodes[0], 1);
1895 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1896 assert_eq!(events.len(), 1);
1897 SendEvent::from_event(events.remove(0))
1899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1901 // channel reserve test with htlc pending output > 0
1902 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1904 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1905 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1906 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1907 ), true, APIError::ChannelUnavailable { ref err },
1908 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1909 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1912 // split the rest to test holding cell
1913 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1914 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1915 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1916 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1918 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1919 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1922 // now see if they go through on both sides
1923 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1924 // but this will stuck in the holding cell
1925 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1926 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1927 check_added_monitors!(nodes[0], 0);
1928 let events = nodes[0].node.get_and_clear_pending_events();
1929 assert_eq!(events.len(), 0);
1931 // test with outbound holding cell amount > 0
1933 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1934 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1935 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1936 ), true, APIError::ChannelUnavailable { ref err },
1937 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1938 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1939 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1942 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1943 // this will also stuck in the holding cell
1944 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1945 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1946 check_added_monitors!(nodes[0], 0);
1947 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1948 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1950 // flush the pending htlc
1951 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1952 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1953 check_added_monitors!(nodes[1], 1);
1955 // the pending htlc should be promoted to committed
1956 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1957 check_added_monitors!(nodes[0], 1);
1958 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1960 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1961 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1962 // No commitment_signed so get_event_msg's assert(len == 1) passes
1963 check_added_monitors!(nodes[0], 1);
1965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1967 check_added_monitors!(nodes[1], 1);
1969 expect_pending_htlcs_forwardable!(nodes[1]);
1971 let ref payment_event_11 = expect_forward!(nodes[1]);
1972 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1973 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1975 expect_pending_htlcs_forwardable!(nodes[2]);
1976 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1978 // flush the htlcs in the holding cell
1979 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1980 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1981 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1982 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1983 expect_pending_htlcs_forwardable!(nodes[1]);
1985 let ref payment_event_3 = expect_forward!(nodes[1]);
1986 assert_eq!(payment_event_3.msgs.len(), 2);
1987 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1988 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1990 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1991 expect_pending_htlcs_forwardable!(nodes[2]);
1993 let events = nodes[2].node.get_and_clear_pending_events();
1994 assert_eq!(events.len(), 2);
1996 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1997 assert_eq!(our_payment_hash_21, *payment_hash);
1998 assert_eq!(recv_value_21, amount_msat);
1999 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2000 assert_eq!(via_channel_id, Some(chan_2.2));
2002 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2003 assert!(payment_preimage.is_none());
2004 assert_eq!(our_payment_secret_21, *payment_secret);
2006 _ => panic!("expected PaymentPurpose::InvoicePayment")
2009 _ => panic!("Unexpected event"),
2012 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2013 assert_eq!(our_payment_hash_22, *payment_hash);
2014 assert_eq!(recv_value_22, amount_msat);
2015 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2016 assert_eq!(via_channel_id, Some(chan_2.2));
2018 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2019 assert!(payment_preimage.is_none());
2020 assert_eq!(our_payment_secret_22, *payment_secret);
2022 _ => panic!("expected PaymentPurpose::InvoicePayment")
2025 _ => panic!("Unexpected event"),
2028 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2029 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2030 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2032 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2033 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2034 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2036 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2037 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2038 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2039 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2040 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2042 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2043 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2047 fn channel_reserve_in_flight_removes() {
2048 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2049 // can send to its counterparty, but due to update ordering, the other side may not yet have
2050 // considered those HTLCs fully removed.
2051 // This tests that we don't count HTLCs which will not be included in the next remote
2052 // commitment transaction towards the reserve value (as it implies no commitment transaction
2053 // will be generated which violates the remote reserve value).
2054 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2056 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2057 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2058 // you only consider the value of the first HTLC, it may not),
2059 // * start routing a third HTLC from A to B,
2060 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2061 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2062 // * deliver the first fulfill from B
2063 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2065 // * deliver A's response CS and RAA.
2066 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2067 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2068 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2069 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2070 let chanmon_cfgs = create_chanmon_cfgs(2);
2071 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2072 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2073 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2074 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2076 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2077 // Route the first two HTLCs.
2078 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2079 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2080 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2082 // Start routing the third HTLC (this is just used to get everyone in the right state).
2083 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2085 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2086 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2087 check_added_monitors!(nodes[0], 1);
2088 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2089 assert_eq!(events.len(), 1);
2090 SendEvent::from_event(events.remove(0))
2093 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2094 // initial fulfill/CS.
2095 nodes[1].node.claim_funds(payment_preimage_1);
2096 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2097 check_added_monitors!(nodes[1], 1);
2098 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2100 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2101 // remove the second HTLC when we send the HTLC back from B to A.
2102 nodes[1].node.claim_funds(payment_preimage_2);
2103 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2104 check_added_monitors!(nodes[1], 1);
2105 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2107 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2108 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2109 check_added_monitors!(nodes[0], 1);
2110 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2111 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2113 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2114 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2115 check_added_monitors!(nodes[1], 1);
2116 // B is already AwaitingRAA, so cant generate a CS here
2117 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2119 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2120 check_added_monitors!(nodes[1], 1);
2121 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2123 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2124 check_added_monitors!(nodes[0], 1);
2125 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2127 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2128 check_added_monitors!(nodes[1], 1);
2129 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2131 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2132 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2133 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2134 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2135 // on-chain as necessary).
2136 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2137 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2138 check_added_monitors!(nodes[0], 1);
2139 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2140 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2142 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2143 check_added_monitors!(nodes[1], 1);
2144 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2146 expect_pending_htlcs_forwardable!(nodes[1]);
2147 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2149 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2150 // resolve the second HTLC from A's point of view.
2151 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2152 check_added_monitors!(nodes[0], 1);
2153 expect_payment_path_successful!(nodes[0]);
2154 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2156 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2157 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2158 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2160 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2161 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2162 check_added_monitors!(nodes[1], 1);
2163 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2164 assert_eq!(events.len(), 1);
2165 SendEvent::from_event(events.remove(0))
2168 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2169 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2170 check_added_monitors!(nodes[0], 1);
2171 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2173 // Now just resolve all the outstanding messages/HTLCs for completeness...
2175 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2176 check_added_monitors!(nodes[1], 1);
2177 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2179 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2180 check_added_monitors!(nodes[1], 1);
2182 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2183 check_added_monitors!(nodes[0], 1);
2184 expect_payment_path_successful!(nodes[0]);
2185 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2187 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2188 check_added_monitors!(nodes[1], 1);
2189 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2191 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2192 check_added_monitors!(nodes[0], 1);
2194 expect_pending_htlcs_forwardable!(nodes[0]);
2195 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2197 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2198 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2202 fn channel_monitor_network_test() {
2203 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2204 // tests that ChannelMonitor is able to recover from various states.
2205 let chanmon_cfgs = create_chanmon_cfgs(5);
2206 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2207 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2208 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2210 // Create some initial channels
2211 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2212 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2213 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2214 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2216 // Make sure all nodes are at the same starting height
2217 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2218 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2219 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2220 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2221 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2223 // Rebalance the network a bit by relaying one payment through all the channels...
2224 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2225 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2226 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229 // Simple case with no pending HTLCs:
2230 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2231 check_added_monitors!(nodes[1], 1);
2232 check_closed_broadcast!(nodes[1], true);
2234 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2235 assert_eq!(node_txn.len(), 1);
2236 mine_transaction(&nodes[0], &node_txn[0]);
2237 check_added_monitors!(nodes[0], 1);
2238 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2240 check_closed_broadcast!(nodes[0], true);
2241 assert_eq!(nodes[0].node.list_channels().len(), 0);
2242 assert_eq!(nodes[1].node.list_channels().len(), 1);
2243 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2244 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2246 // One pending HTLC is discarded by the force-close:
2247 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2249 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2250 // broadcasted until we reach the timelock time).
2251 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2252 check_closed_broadcast!(nodes[1], true);
2253 check_added_monitors!(nodes[1], 1);
2255 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2256 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2257 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2258 mine_transaction(&nodes[2], &node_txn[0]);
2259 check_added_monitors!(nodes[2], 1);
2260 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2262 check_closed_broadcast!(nodes[2], true);
2263 assert_eq!(nodes[1].node.list_channels().len(), 0);
2264 assert_eq!(nodes[2].node.list_channels().len(), 1);
2265 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2266 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2268 macro_rules! claim_funds {
2269 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2271 $node.node.claim_funds($preimage);
2272 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2273 check_added_monitors!($node, 1);
2275 let events = $node.node.get_and_clear_pending_msg_events();
2276 assert_eq!(events.len(), 1);
2278 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2279 assert!(update_add_htlcs.is_empty());
2280 assert!(update_fail_htlcs.is_empty());
2281 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2283 _ => panic!("Unexpected event"),
2289 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2290 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2291 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2292 check_added_monitors!(nodes[2], 1);
2293 check_closed_broadcast!(nodes[2], true);
2294 let node2_commitment_txid;
2296 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2297 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2298 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2299 node2_commitment_txid = node_txn[0].txid();
2301 // Claim the payment on nodes[3], giving it knowledge of the preimage
2302 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2303 mine_transaction(&nodes[3], &node_txn[0]);
2304 check_added_monitors!(nodes[3], 1);
2305 check_preimage_claim(&nodes[3], &node_txn);
2307 check_closed_broadcast!(nodes[3], true);
2308 assert_eq!(nodes[2].node.list_channels().len(), 0);
2309 assert_eq!(nodes[3].node.list_channels().len(), 1);
2310 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2311 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2313 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2314 // confusing us in the following tests.
2315 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2317 // One pending HTLC to time out:
2318 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2319 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2322 let (close_chan_update_1, close_chan_update_2) = {
2323 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2324 let events = nodes[3].node.get_and_clear_pending_msg_events();
2325 assert_eq!(events.len(), 2);
2326 let close_chan_update_1 = match events[0] {
2327 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2330 _ => panic!("Unexpected event"),
2333 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2336 _ => panic!("Unexpected event"),
2338 check_added_monitors!(nodes[3], 1);
2340 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2342 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2343 node_txn.retain(|tx| {
2344 if tx.input[0].previous_output.txid == node2_commitment_txid {
2350 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2352 // Claim the payment on nodes[4], giving it knowledge of the preimage
2353 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2355 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2356 let events = nodes[4].node.get_and_clear_pending_msg_events();
2357 assert_eq!(events.len(), 2);
2358 let close_chan_update_2 = match events[0] {
2359 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2362 _ => panic!("Unexpected event"),
2365 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2366 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2368 _ => panic!("Unexpected event"),
2370 check_added_monitors!(nodes[4], 1);
2371 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2373 mine_transaction(&nodes[4], &node_txn[0]);
2374 check_preimage_claim(&nodes[4], &node_txn);
2375 (close_chan_update_1, close_chan_update_2)
2377 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2378 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2379 assert_eq!(nodes[3].node.list_channels().len(), 0);
2380 assert_eq!(nodes[4].node.list_channels().len(), 0);
2382 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2383 ChannelMonitorUpdateStatus::Completed);
2384 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2385 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2389 fn test_justice_tx_htlc_timeout() {
2390 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2391 let mut alice_config = UserConfig::default();
2392 alice_config.channel_handshake_config.announced_channel = true;
2393 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2394 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2395 let mut bob_config = UserConfig::default();
2396 bob_config.channel_handshake_config.announced_channel = true;
2397 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2398 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2399 let user_cfgs = [Some(alice_config), Some(bob_config)];
2400 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2401 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2402 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2405 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2406 // Create some new channels:
2407 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2409 // A pending HTLC which will be revoked:
2410 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2411 // Get the will-be-revoked local txn from nodes[0]
2412 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2413 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2414 assert_eq!(revoked_local_txn[0].input.len(), 1);
2415 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2416 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2417 assert_eq!(revoked_local_txn[1].input.len(), 1);
2418 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2419 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2420 // Revoke the old state
2421 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2424 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2426 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2427 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2428 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2429 check_spends!(node_txn[0], revoked_local_txn[0]);
2430 node_txn.swap_remove(0);
2432 check_added_monitors!(nodes[1], 1);
2433 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2434 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2436 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2437 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2438 // Verify broadcast of revoked HTLC-timeout
2439 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2440 check_added_monitors!(nodes[0], 1);
2441 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2442 // Broadcast revoked HTLC-timeout on node 1
2443 mine_transaction(&nodes[1], &node_txn[1]);
2444 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2446 get_announce_close_broadcast_events(&nodes, 0, 1);
2447 assert_eq!(nodes[0].node.list_channels().len(), 0);
2448 assert_eq!(nodes[1].node.list_channels().len(), 0);
2452 fn test_justice_tx_htlc_success() {
2453 // Test justice txn built on revoked HTLC-Success tx, against both sides
2454 let mut alice_config = UserConfig::default();
2455 alice_config.channel_handshake_config.announced_channel = true;
2456 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2457 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2458 let mut bob_config = UserConfig::default();
2459 bob_config.channel_handshake_config.announced_channel = true;
2460 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2461 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2462 let user_cfgs = [Some(alice_config), Some(bob_config)];
2463 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2464 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2465 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2468 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2469 // Create some new channels:
2470 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2472 // A pending HTLC which will be revoked:
2473 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2474 // Get the will-be-revoked local txn from B
2475 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2476 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2477 assert_eq!(revoked_local_txn[0].input.len(), 1);
2478 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2479 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2480 // Revoke the old state
2481 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2483 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2485 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2486 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2487 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2489 check_spends!(node_txn[0], revoked_local_txn[0]);
2490 node_txn.swap_remove(0);
2492 check_added_monitors!(nodes[0], 1);
2493 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2495 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2496 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2497 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2498 check_added_monitors!(nodes[1], 1);
2499 mine_transaction(&nodes[0], &node_txn[1]);
2500 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2501 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2503 get_announce_close_broadcast_events(&nodes, 0, 1);
2504 assert_eq!(nodes[0].node.list_channels().len(), 0);
2505 assert_eq!(nodes[1].node.list_channels().len(), 0);
2509 fn revoked_output_claim() {
2510 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2511 // transaction is broadcast by its counterparty
2512 let chanmon_cfgs = create_chanmon_cfgs(2);
2513 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2514 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2515 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2517 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2518 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2519 assert_eq!(revoked_local_txn.len(), 1);
2520 // Only output is the full channel value back to nodes[0]:
2521 assert_eq!(revoked_local_txn[0].output.len(), 1);
2522 // Send a payment through, updating everyone's latest commitment txn
2523 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2525 // Inform nodes[1] that nodes[0] broadcast a stale tx
2526 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2527 check_added_monitors!(nodes[1], 1);
2528 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2529 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2530 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2532 check_spends!(node_txn[0], revoked_local_txn[0]);
2534 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2535 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2536 get_announce_close_broadcast_events(&nodes, 0, 1);
2537 check_added_monitors!(nodes[0], 1);
2538 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2542 fn claim_htlc_outputs_shared_tx() {
2543 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2544 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2545 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2550 // Create some new channel:
2551 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2553 // Rebalance the network to generate htlc in the two directions
2554 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2555 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2556 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2557 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2559 // Get the will-be-revoked local txn from node[0]
2560 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2561 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2562 assert_eq!(revoked_local_txn[0].input.len(), 1);
2563 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2564 assert_eq!(revoked_local_txn[1].input.len(), 1);
2565 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2566 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2567 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2569 //Revoke the old state
2570 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2573 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2574 check_added_monitors!(nodes[0], 1);
2575 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2576 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2577 check_added_monitors!(nodes[1], 1);
2578 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2579 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2580 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2582 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2583 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2585 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2586 check_spends!(node_txn[0], revoked_local_txn[0]);
2588 let mut witness_lens = BTreeSet::new();
2589 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2590 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2591 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2592 assert_eq!(witness_lens.len(), 3);
2593 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2594 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2595 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2597 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2598 // ANTI_REORG_DELAY confirmations.
2599 mine_transaction(&nodes[1], &node_txn[0]);
2600 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2601 expect_payment_failed!(nodes[1], payment_hash_2, false);
2603 get_announce_close_broadcast_events(&nodes, 0, 1);
2604 assert_eq!(nodes[0].node.list_channels().len(), 0);
2605 assert_eq!(nodes[1].node.list_channels().len(), 0);
2609 fn claim_htlc_outputs_single_tx() {
2610 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2611 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2612 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2617 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2619 // Rebalance the network to generate htlc in the two directions
2620 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2621 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2622 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2623 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2624 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2626 // Get the will-be-revoked local txn from node[0]
2627 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2629 //Revoke the old state
2630 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2633 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2634 check_added_monitors!(nodes[0], 1);
2635 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2636 check_added_monitors!(nodes[1], 1);
2637 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2638 let mut events = nodes[0].node.get_and_clear_pending_events();
2639 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2640 match events.last().unwrap() {
2641 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2642 _ => panic!("Unexpected event"),
2645 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2646 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2648 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2650 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2651 assert_eq!(node_txn[0].input.len(), 1);
2652 check_spends!(node_txn[0], chan_1.3);
2653 assert_eq!(node_txn[1].input.len(), 1);
2654 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2655 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2656 check_spends!(node_txn[1], node_txn[0]);
2658 // Filter out any non justice transactions.
2659 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2660 assert!(node_txn.len() > 3);
2662 assert_eq!(node_txn[0].input.len(), 1);
2663 assert_eq!(node_txn[1].input.len(), 1);
2664 assert_eq!(node_txn[2].input.len(), 1);
2666 check_spends!(node_txn[0], revoked_local_txn[0]);
2667 check_spends!(node_txn[1], revoked_local_txn[0]);
2668 check_spends!(node_txn[2], revoked_local_txn[0]);
2670 let mut witness_lens = BTreeSet::new();
2671 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2672 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2673 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2674 assert_eq!(witness_lens.len(), 3);
2675 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2676 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2677 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2679 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2680 // ANTI_REORG_DELAY confirmations.
2681 mine_transaction(&nodes[1], &node_txn[0]);
2682 mine_transaction(&nodes[1], &node_txn[1]);
2683 mine_transaction(&nodes[1], &node_txn[2]);
2684 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2685 expect_payment_failed!(nodes[1], payment_hash_2, false);
2687 get_announce_close_broadcast_events(&nodes, 0, 1);
2688 assert_eq!(nodes[0].node.list_channels().len(), 0);
2689 assert_eq!(nodes[1].node.list_channels().len(), 0);
2693 fn test_htlc_on_chain_success() {
2694 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2695 // the preimage backward accordingly. So here we test that ChannelManager is
2696 // broadcasting the right event to other nodes in payment path.
2697 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2698 // A --------------------> B ----------------------> C (preimage)
2699 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2700 // commitment transaction was broadcast.
2701 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2703 // B should be able to claim via preimage if A then broadcasts its local tx.
2704 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2705 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2706 // PaymentSent event).
2708 let chanmon_cfgs = create_chanmon_cfgs(3);
2709 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2710 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2711 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2713 // Create some initial channels
2714 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2715 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2717 // Ensure all nodes are at the same height
2718 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2719 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2720 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2721 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2723 // Rebalance the network a bit by relaying one payment through all the channels...
2724 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2725 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2727 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2728 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2730 // Broadcast legit commitment tx from C on B's chain
2731 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2732 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2733 assert_eq!(commitment_tx.len(), 1);
2734 check_spends!(commitment_tx[0], chan_2.3);
2735 nodes[2].node.claim_funds(our_payment_preimage);
2736 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2737 nodes[2].node.claim_funds(our_payment_preimage_2);
2738 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2739 check_added_monitors!(nodes[2], 2);
2740 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2741 assert!(updates.update_add_htlcs.is_empty());
2742 assert!(updates.update_fail_htlcs.is_empty());
2743 assert!(updates.update_fail_malformed_htlcs.is_empty());
2744 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2746 mine_transaction(&nodes[2], &commitment_tx[0]);
2747 check_closed_broadcast!(nodes[2], true);
2748 check_added_monitors!(nodes[2], 1);
2749 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2750 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2751 assert_eq!(node_txn.len(), 2);
2752 check_spends!(node_txn[0], commitment_tx[0]);
2753 check_spends!(node_txn[1], commitment_tx[0]);
2754 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2755 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2756 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2757 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2758 assert_eq!(node_txn[0].lock_time.0, 0);
2759 assert_eq!(node_txn[1].lock_time.0, 0);
2761 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2762 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2763 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2765 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2766 assert_eq!(added_monitors.len(), 1);
2767 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2768 added_monitors.clear();
2770 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2771 assert_eq!(forwarded_events.len(), 3);
2772 match forwarded_events[0] {
2773 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2774 _ => panic!("Unexpected event"),
2776 let chan_id = Some(chan_1.2);
2777 match forwarded_events[1] {
2778 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2779 assert_eq!(fee_earned_msat, Some(1000));
2780 assert_eq!(prev_channel_id, chan_id);
2781 assert_eq!(claim_from_onchain_tx, true);
2782 assert_eq!(next_channel_id, Some(chan_2.2));
2783 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2787 match forwarded_events[2] {
2788 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2789 assert_eq!(fee_earned_msat, Some(1000));
2790 assert_eq!(prev_channel_id, chan_id);
2791 assert_eq!(claim_from_onchain_tx, true);
2792 assert_eq!(next_channel_id, Some(chan_2.2));
2793 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2797 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2799 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2800 assert_eq!(added_monitors.len(), 2);
2801 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2802 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2803 added_monitors.clear();
2805 assert_eq!(events.len(), 3);
2807 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2808 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2810 match nodes_2_event {
2811 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2812 _ => panic!("Unexpected event"),
2815 match nodes_0_event {
2816 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2817 assert!(update_add_htlcs.is_empty());
2818 assert!(update_fail_htlcs.is_empty());
2819 assert_eq!(update_fulfill_htlcs.len(), 1);
2820 assert!(update_fail_malformed_htlcs.is_empty());
2821 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2823 _ => panic!("Unexpected event"),
2826 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2828 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2829 _ => panic!("Unexpected event"),
2832 macro_rules! check_tx_local_broadcast {
2833 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2834 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2835 assert_eq!(node_txn.len(), 2);
2836 // Node[1]: 2 * HTLC-timeout tx
2837 // Node[0]: 2 * HTLC-timeout tx
2838 check_spends!(node_txn[0], $commitment_tx);
2839 check_spends!(node_txn[1], $commitment_tx);
2840 assert_ne!(node_txn[0].lock_time.0, 0);
2841 assert_ne!(node_txn[1].lock_time.0, 0);
2843 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2846 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2848 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2849 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2850 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2851 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2857 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2859 // Broadcast legit commitment tx from A on B's chain
2860 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2861 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2862 check_spends!(node_a_commitment_tx[0], chan_1.3);
2863 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2864 check_closed_broadcast!(nodes[1], true);
2865 check_added_monitors!(nodes[1], 1);
2866 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2867 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2868 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2869 let commitment_spend =
2870 if node_txn.len() == 1 {
2873 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2874 // FullBlockViaListen
2875 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2876 check_spends!(node_txn[1], commitment_tx[0]);
2877 check_spends!(node_txn[2], commitment_tx[0]);
2878 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2881 check_spends!(node_txn[0], commitment_tx[0]);
2882 check_spends!(node_txn[1], commitment_tx[0]);
2883 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2888 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2889 assert_eq!(commitment_spend.input.len(), 2);
2890 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2891 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2892 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2893 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2894 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2895 // we already checked the same situation with A.
2897 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2898 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2899 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2900 check_closed_broadcast!(nodes[0], true);
2901 check_added_monitors!(nodes[0], 1);
2902 let events = nodes[0].node.get_and_clear_pending_events();
2903 assert_eq!(events.len(), 5);
2904 let mut first_claimed = false;
2905 for event in events {
2907 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2908 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2909 assert!(!first_claimed);
2910 first_claimed = true;
2912 assert_eq!(payment_preimage, our_payment_preimage_2);
2913 assert_eq!(payment_hash, payment_hash_2);
2916 Event::PaymentPathSuccessful { .. } => {},
2917 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2918 _ => panic!("Unexpected event"),
2921 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2924 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2925 // Test that in case of a unilateral close onchain, we detect the state of output and
2926 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2927 // broadcasting the right event to other nodes in payment path.
2928 // A ------------------> B ----------------------> C (timeout)
2929 // B's commitment tx C's commitment tx
2931 // B's HTLC timeout tx B's timeout tx
2933 let chanmon_cfgs = create_chanmon_cfgs(3);
2934 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2935 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2936 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2937 *nodes[0].connect_style.borrow_mut() = connect_style;
2938 *nodes[1].connect_style.borrow_mut() = connect_style;
2939 *nodes[2].connect_style.borrow_mut() = connect_style;
2941 // Create some intial channels
2942 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2943 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2945 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2946 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2947 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2949 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2951 // Broadcast legit commitment tx from C on B's chain
2952 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2953 check_spends!(commitment_tx[0], chan_2.3);
2954 nodes[2].node.fail_htlc_backwards(&payment_hash);
2955 check_added_monitors!(nodes[2], 0);
2956 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2957 check_added_monitors!(nodes[2], 1);
2959 let events = nodes[2].node.get_and_clear_pending_msg_events();
2960 assert_eq!(events.len(), 1);
2962 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2963 assert!(update_add_htlcs.is_empty());
2964 assert!(!update_fail_htlcs.is_empty());
2965 assert!(update_fulfill_htlcs.is_empty());
2966 assert!(update_fail_malformed_htlcs.is_empty());
2967 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2969 _ => panic!("Unexpected event"),
2971 mine_transaction(&nodes[2], &commitment_tx[0]);
2972 check_closed_broadcast!(nodes[2], true);
2973 check_added_monitors!(nodes[2], 1);
2974 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2975 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2976 assert_eq!(node_txn.len(), 0);
2978 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2979 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2980 mine_transaction(&nodes[1], &commitment_tx[0]);
2981 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2982 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2984 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2985 if nodes[1].connect_style.borrow().skips_blocks() {
2986 assert_eq!(txn.len(), 1);
2988 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2990 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2991 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2995 mine_transaction(&nodes[1], &timeout_tx);
2996 check_added_monitors!(nodes[1], 1);
2997 check_closed_broadcast!(nodes[1], true);
2999 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3001 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3002 check_added_monitors!(nodes[1], 1);
3003 let events = nodes[1].node.get_and_clear_pending_msg_events();
3004 assert_eq!(events.len(), 1);
3006 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3007 assert!(update_add_htlcs.is_empty());
3008 assert!(!update_fail_htlcs.is_empty());
3009 assert!(update_fulfill_htlcs.is_empty());
3010 assert!(update_fail_malformed_htlcs.is_empty());
3011 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3013 _ => panic!("Unexpected event"),
3016 // Broadcast legit commitment tx from B on A's chain
3017 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3018 check_spends!(commitment_tx[0], chan_1.3);
3020 mine_transaction(&nodes[0], &commitment_tx[0]);
3021 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3023 check_closed_broadcast!(nodes[0], true);
3024 check_added_monitors!(nodes[0], 1);
3025 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3026 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3027 assert_eq!(node_txn.len(), 1);
3028 check_spends!(node_txn[0], commitment_tx[0]);
3029 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3033 fn test_htlc_on_chain_timeout() {
3034 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3035 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3036 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3040 fn test_simple_commitment_revoked_fail_backward() {
3041 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3042 // and fail backward accordingly.
3044 let chanmon_cfgs = create_chanmon_cfgs(3);
3045 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3046 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3047 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3049 // Create some initial channels
3050 create_announced_chan_between_nodes(&nodes, 0, 1);
3051 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3053 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3054 // Get the will-be-revoked local txn from nodes[2]
3055 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3056 // Revoke the old state
3057 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3059 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3061 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3062 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3063 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3064 check_added_monitors!(nodes[1], 1);
3065 check_closed_broadcast!(nodes[1], true);
3067 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3068 check_added_monitors!(nodes[1], 1);
3069 let events = nodes[1].node.get_and_clear_pending_msg_events();
3070 assert_eq!(events.len(), 1);
3072 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3073 assert!(update_add_htlcs.is_empty());
3074 assert_eq!(update_fail_htlcs.len(), 1);
3075 assert!(update_fulfill_htlcs.is_empty());
3076 assert!(update_fail_malformed_htlcs.is_empty());
3077 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3079 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3080 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3081 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3083 _ => panic!("Unexpected event"),
3087 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3088 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3089 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3090 // commitment transaction anymore.
3091 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3092 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3093 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3094 // technically disallowed and we should probably handle it reasonably.
3095 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3096 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3098 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3099 // commitment_signed (implying it will be in the latest remote commitment transaction).
3100 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3101 // and once they revoke the previous commitment transaction (allowing us to send a new
3102 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3103 let chanmon_cfgs = create_chanmon_cfgs(3);
3104 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3105 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3106 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3108 // Create some initial channels
3109 create_announced_chan_between_nodes(&nodes, 0, 1);
3110 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3112 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3113 // Get the will-be-revoked local txn from nodes[2]
3114 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3115 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3116 // Revoke the old state
3117 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3119 let value = if use_dust {
3120 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3121 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3122 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3123 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3126 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3127 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3128 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3131 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3132 check_added_monitors!(nodes[2], 1);
3133 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3134 assert!(updates.update_add_htlcs.is_empty());
3135 assert!(updates.update_fulfill_htlcs.is_empty());
3136 assert!(updates.update_fail_malformed_htlcs.is_empty());
3137 assert_eq!(updates.update_fail_htlcs.len(), 1);
3138 assert!(updates.update_fee.is_none());
3139 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3140 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3141 // Drop the last RAA from 3 -> 2
3143 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3144 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3145 check_added_monitors!(nodes[2], 1);
3146 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3147 assert!(updates.update_add_htlcs.is_empty());
3148 assert!(updates.update_fulfill_htlcs.is_empty());
3149 assert!(updates.update_fail_malformed_htlcs.is_empty());
3150 assert_eq!(updates.update_fail_htlcs.len(), 1);
3151 assert!(updates.update_fee.is_none());
3152 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3153 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3154 check_added_monitors!(nodes[1], 1);
3155 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3156 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3157 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3158 check_added_monitors!(nodes[2], 1);
3160 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3161 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3162 check_added_monitors!(nodes[2], 1);
3163 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3164 assert!(updates.update_add_htlcs.is_empty());
3165 assert!(updates.update_fulfill_htlcs.is_empty());
3166 assert!(updates.update_fail_malformed_htlcs.is_empty());
3167 assert_eq!(updates.update_fail_htlcs.len(), 1);
3168 assert!(updates.update_fee.is_none());
3169 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3170 // At this point first_payment_hash has dropped out of the latest two commitment
3171 // transactions that nodes[1] is tracking...
3172 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3173 check_added_monitors!(nodes[1], 1);
3174 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3175 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3176 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3177 check_added_monitors!(nodes[2], 1);
3179 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3180 // on nodes[2]'s RAA.
3181 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3182 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3183 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3184 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3185 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3186 check_added_monitors!(nodes[1], 0);
3189 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3190 // One monitor for the new revocation preimage, no second on as we won't generate a new
3191 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3192 check_added_monitors!(nodes[1], 1);
3193 let events = nodes[1].node.get_and_clear_pending_events();
3194 assert_eq!(events.len(), 2);
3196 Event::PendingHTLCsForwardable { .. } => { },
3197 _ => panic!("Unexpected event"),
3200 Event::HTLCHandlingFailed { .. } => { },
3201 _ => panic!("Unexpected event"),
3203 // Deliberately don't process the pending fail-back so they all fail back at once after
3204 // block connection just like the !deliver_bs_raa case
3207 let mut failed_htlcs = HashSet::new();
3208 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3210 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3211 check_added_monitors!(nodes[1], 1);
3212 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3214 let events = nodes[1].node.get_and_clear_pending_events();
3215 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3217 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3218 _ => panic!("Unexepected event"),
3221 Event::PaymentPathFailed { ref payment_hash, .. } => {
3222 assert_eq!(*payment_hash, fourth_payment_hash);
3224 _ => panic!("Unexpected event"),
3227 Event::PaymentFailed { ref payment_hash, .. } => {
3228 assert_eq!(*payment_hash, fourth_payment_hash);
3230 _ => panic!("Unexpected event"),
3233 nodes[1].node.process_pending_htlc_forwards();
3234 check_added_monitors!(nodes[1], 1);
3236 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3237 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3240 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3241 match nodes_2_event {
3242 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3243 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3244 assert_eq!(update_add_htlcs.len(), 1);
3245 assert!(update_fulfill_htlcs.is_empty());
3246 assert!(update_fail_htlcs.is_empty());
3247 assert!(update_fail_malformed_htlcs.is_empty());
3249 _ => panic!("Unexpected event"),
3253 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3254 match nodes_2_event {
3255 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3256 assert_eq!(channel_id, chan_2.2);
3257 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3259 _ => panic!("Unexpected event"),
3262 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3263 match nodes_0_event {
3264 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3265 assert!(update_add_htlcs.is_empty());
3266 assert_eq!(update_fail_htlcs.len(), 3);
3267 assert!(update_fulfill_htlcs.is_empty());
3268 assert!(update_fail_malformed_htlcs.is_empty());
3269 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3271 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3272 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3273 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3275 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3277 let events = nodes[0].node.get_and_clear_pending_events();
3278 assert_eq!(events.len(), 6);
3280 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3281 assert!(failed_htlcs.insert(payment_hash.0));
3282 // If we delivered B's RAA we got an unknown preimage error, not something
3283 // that we should update our routing table for.
3284 if !deliver_bs_raa {
3285 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3288 _ => panic!("Unexpected event"),
3291 Event::PaymentFailed { ref payment_hash, .. } => {
3292 assert_eq!(*payment_hash, first_payment_hash);
3294 _ => panic!("Unexpected event"),
3297 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3298 assert!(failed_htlcs.insert(payment_hash.0));
3300 _ => panic!("Unexpected event"),
3303 Event::PaymentFailed { ref payment_hash, .. } => {
3304 assert_eq!(*payment_hash, second_payment_hash);
3306 _ => panic!("Unexpected event"),
3309 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3310 assert!(failed_htlcs.insert(payment_hash.0));
3312 _ => panic!("Unexpected event"),
3315 Event::PaymentFailed { ref payment_hash, .. } => {
3316 assert_eq!(*payment_hash, third_payment_hash);
3318 _ => panic!("Unexpected event"),
3321 _ => panic!("Unexpected event"),
3324 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3326 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3327 _ => panic!("Unexpected event"),
3330 assert!(failed_htlcs.contains(&first_payment_hash.0));
3331 assert!(failed_htlcs.contains(&second_payment_hash.0));
3332 assert!(failed_htlcs.contains(&third_payment_hash.0));
3336 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3337 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3338 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3339 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3340 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3344 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3345 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3346 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3347 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3348 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3352 fn fail_backward_pending_htlc_upon_channel_failure() {
3353 let chanmon_cfgs = create_chanmon_cfgs(2);
3354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3356 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3359 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3361 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3362 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3363 PaymentId(payment_hash.0)).unwrap();
3364 check_added_monitors!(nodes[0], 1);
3366 let payment_event = {
3367 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3368 assert_eq!(events.len(), 1);
3369 SendEvent::from_event(events.remove(0))
3371 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3372 assert_eq!(payment_event.msgs.len(), 1);
3375 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3376 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3378 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3379 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3380 check_added_monitors!(nodes[0], 0);
3382 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3385 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3387 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3389 let secp_ctx = Secp256k1::new();
3390 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3391 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3392 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3393 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3394 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3395 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3397 // Send a 0-msat update_add_htlc to fail the channel.
3398 let update_add_htlc = msgs::UpdateAddHTLC {
3404 onion_routing_packet,
3406 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3408 let events = nodes[0].node.get_and_clear_pending_events();
3409 assert_eq!(events.len(), 3);
3410 // Check that Alice fails backward the pending HTLC from the second payment.
3412 Event::PaymentPathFailed { payment_hash, .. } => {
3413 assert_eq!(payment_hash, failed_payment_hash);
3415 _ => panic!("Unexpected event"),
3418 Event::PaymentFailed { payment_hash, .. } => {
3419 assert_eq!(payment_hash, failed_payment_hash);
3421 _ => panic!("Unexpected event"),
3424 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3425 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3427 _ => panic!("Unexpected event {:?}", events[1]),
3429 check_closed_broadcast!(nodes[0], true);
3430 check_added_monitors!(nodes[0], 1);
3434 fn test_htlc_ignore_latest_remote_commitment() {
3435 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3436 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3437 let chanmon_cfgs = create_chanmon_cfgs(2);
3438 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3439 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3440 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3441 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3442 // We rely on the ability to connect a block redundantly, which isn't allowed via
3443 // `chain::Listen`, so we never run the test if we randomly get assigned that
3447 create_announced_chan_between_nodes(&nodes, 0, 1);
3449 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3450 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3451 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3452 check_closed_broadcast!(nodes[0], true);
3453 check_added_monitors!(nodes[0], 1);
3454 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3456 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3457 assert_eq!(node_txn.len(), 3);
3458 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3460 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3461 connect_block(&nodes[1], &block);
3462 check_closed_broadcast!(nodes[1], true);
3463 check_added_monitors!(nodes[1], 1);
3464 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3466 // Duplicate the connect_block call since this may happen due to other listeners
3467 // registering new transactions
3468 connect_block(&nodes[1], &block);
3472 fn test_force_close_fail_back() {
3473 // Check which HTLCs are failed-backwards on channel force-closure
3474 let chanmon_cfgs = create_chanmon_cfgs(3);
3475 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3476 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3477 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3478 create_announced_chan_between_nodes(&nodes, 0, 1);
3479 create_announced_chan_between_nodes(&nodes, 1, 2);
3481 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3483 let mut payment_event = {
3484 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3485 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3486 check_added_monitors!(nodes[0], 1);
3488 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3489 assert_eq!(events.len(), 1);
3490 SendEvent::from_event(events.remove(0))
3493 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3494 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3496 expect_pending_htlcs_forwardable!(nodes[1]);
3498 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3499 assert_eq!(events_2.len(), 1);
3500 payment_event = SendEvent::from_event(events_2.remove(0));
3501 assert_eq!(payment_event.msgs.len(), 1);
3503 check_added_monitors!(nodes[1], 1);
3504 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3505 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3506 check_added_monitors!(nodes[2], 1);
3507 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3509 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3510 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3511 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3513 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3514 check_closed_broadcast!(nodes[2], true);
3515 check_added_monitors!(nodes[2], 1);
3516 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3518 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3519 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3520 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3521 // back to nodes[1] upon timeout otherwise.
3522 assert_eq!(node_txn.len(), 1);
3526 mine_transaction(&nodes[1], &tx);
3528 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3529 check_closed_broadcast!(nodes[1], true);
3530 check_added_monitors!(nodes[1], 1);
3531 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3533 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3535 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3536 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3538 mine_transaction(&nodes[2], &tx);
3539 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3540 assert_eq!(node_txn.len(), 1);
3541 assert_eq!(node_txn[0].input.len(), 1);
3542 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3543 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3544 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3546 check_spends!(node_txn[0], tx);
3550 fn test_dup_events_on_peer_disconnect() {
3551 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3552 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3553 // as we used to generate the event immediately upon receipt of the payment preimage in the
3554 // update_fulfill_htlc message.
3556 let chanmon_cfgs = create_chanmon_cfgs(2);
3557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3559 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3560 create_announced_chan_between_nodes(&nodes, 0, 1);
3562 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3564 nodes[1].node.claim_funds(payment_preimage);
3565 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3566 check_added_monitors!(nodes[1], 1);
3567 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3568 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3569 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3574 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575 expect_payment_path_successful!(nodes[0]);
3579 fn test_peer_disconnected_before_funding_broadcasted() {
3580 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3581 // before the funding transaction has been broadcasted.
3582 let chanmon_cfgs = create_chanmon_cfgs(2);
3583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3585 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3587 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3588 // broadcasted, even though it's created by `nodes[0]`.
3589 let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
3590 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3591 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3592 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3593 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3595 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3596 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3598 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3600 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3601 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3603 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3604 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3607 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3610 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3611 // disconnected before the funding transaction was broadcasted.
3612 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3613 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3615 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3616 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3620 fn test_simple_peer_disconnect() {
3621 // Test that we can reconnect when there are no lost messages
3622 let chanmon_cfgs = create_chanmon_cfgs(3);
3623 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3624 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3625 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3626 create_announced_chan_between_nodes(&nodes, 0, 1);
3627 create_announced_chan_between_nodes(&nodes, 1, 2);
3629 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3630 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3631 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3633 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3634 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3635 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3636 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3638 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3639 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3640 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3642 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3643 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3644 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3645 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3648 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3650 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3651 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3653 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3655 let events = nodes[0].node.get_and_clear_pending_events();
3656 assert_eq!(events.len(), 4);
3658 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3659 assert_eq!(payment_preimage, payment_preimage_3);
3660 assert_eq!(payment_hash, payment_hash_3);
3662 _ => panic!("Unexpected event"),
3665 Event::PaymentPathSuccessful { .. } => {},
3666 _ => panic!("Unexpected event"),
3669 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3670 assert_eq!(payment_hash, payment_hash_5);
3671 assert!(payment_failed_permanently);
3673 _ => panic!("Unexpected event"),
3676 Event::PaymentFailed { payment_hash, .. } => {
3677 assert_eq!(payment_hash, payment_hash_5);
3679 _ => panic!("Unexpected event"),
3683 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3684 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3687 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3688 // Test that we can reconnect when in-flight HTLC updates get dropped
3689 let chanmon_cfgs = create_chanmon_cfgs(2);
3690 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3691 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3692 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3694 let mut as_channel_ready = None;
3695 let channel_id = if messages_delivered == 0 {
3696 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3697 as_channel_ready = Some(channel_ready);
3698 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3699 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3700 // it before the channel_reestablish message.
3703 create_announced_chan_between_nodes(&nodes, 0, 1).2
3706 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3708 let payment_event = {
3709 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3710 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3711 check_added_monitors!(nodes[0], 1);
3713 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3714 assert_eq!(events.len(), 1);
3715 SendEvent::from_event(events.remove(0))
3717 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3719 if messages_delivered < 2 {
3720 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3722 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3723 if messages_delivered >= 3 {
3724 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3725 check_added_monitors!(nodes[1], 1);
3726 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3728 if messages_delivered >= 4 {
3729 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3730 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3731 check_added_monitors!(nodes[0], 1);
3733 if messages_delivered >= 5 {
3734 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3735 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3736 // No commitment_signed so get_event_msg's assert(len == 1) passes
3737 check_added_monitors!(nodes[0], 1);
3739 if messages_delivered >= 6 {
3740 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3741 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3742 check_added_monitors!(nodes[1], 1);
3749 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3750 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3751 if messages_delivered < 3 {
3752 if simulate_broken_lnd {
3753 // lnd has a long-standing bug where they send a channel_ready prior to a
3754 // channel_reestablish if you reconnect prior to channel_ready time.
3756 // Here we simulate that behavior, delivering a channel_ready immediately on
3757 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3758 // in `reconnect_nodes` but we currently don't fail based on that.
3760 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3761 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3763 // Even if the channel_ready messages get exchanged, as long as nothing further was
3764 // received on either side, both sides will need to resend them.
3765 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3766 } else if messages_delivered == 3 {
3767 // nodes[0] still wants its RAA + commitment_signed
3768 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3769 } else if messages_delivered == 4 {
3770 // nodes[0] still wants its commitment_signed
3771 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3772 } else if messages_delivered == 5 {
3773 // nodes[1] still wants its final RAA
3774 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3775 } else if messages_delivered == 6 {
3776 // Everything was delivered...
3777 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780 let events_1 = nodes[1].node.get_and_clear_pending_events();
3781 if messages_delivered == 0 {
3782 assert_eq!(events_1.len(), 2);
3784 Event::ChannelReady { .. } => { },
3785 _ => panic!("Unexpected event"),
3788 Event::PendingHTLCsForwardable { .. } => { },
3789 _ => panic!("Unexpected event"),
3792 assert_eq!(events_1.len(), 1);
3794 Event::PendingHTLCsForwardable { .. } => { },
3795 _ => panic!("Unexpected event"),
3799 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3800 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803 nodes[1].node.process_pending_htlc_forwards();
3805 let events_2 = nodes[1].node.get_and_clear_pending_events();
3806 assert_eq!(events_2.len(), 1);
3808 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3809 assert_eq!(payment_hash_1, *payment_hash);
3810 assert_eq!(amount_msat, 1_000_000);
3811 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3812 assert_eq!(via_channel_id, Some(channel_id));
3814 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3815 assert!(payment_preimage.is_none());
3816 assert_eq!(payment_secret_1, *payment_secret);
3818 _ => panic!("expected PaymentPurpose::InvoicePayment")
3821 _ => panic!("Unexpected event"),
3824 nodes[1].node.claim_funds(payment_preimage_1);
3825 check_added_monitors!(nodes[1], 1);
3826 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3828 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3829 assert_eq!(events_3.len(), 1);
3830 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3831 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3832 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3833 assert!(updates.update_add_htlcs.is_empty());
3834 assert!(updates.update_fail_htlcs.is_empty());
3835 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3836 assert!(updates.update_fail_malformed_htlcs.is_empty());
3837 assert!(updates.update_fee.is_none());
3838 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3840 _ => panic!("Unexpected event"),
3843 if messages_delivered >= 1 {
3844 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3846 let events_4 = nodes[0].node.get_and_clear_pending_events();
3847 assert_eq!(events_4.len(), 1);
3849 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3850 assert_eq!(payment_preimage_1, *payment_preimage);
3851 assert_eq!(payment_hash_1, *payment_hash);
3853 _ => panic!("Unexpected event"),
3856 if messages_delivered >= 2 {
3857 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3858 check_added_monitors!(nodes[0], 1);
3859 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3861 if messages_delivered >= 3 {
3862 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3863 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3864 check_added_monitors!(nodes[1], 1);
3866 if messages_delivered >= 4 {
3867 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3868 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3869 // No commitment_signed so get_event_msg's assert(len == 1) passes
3870 check_added_monitors!(nodes[1], 1);
3872 if messages_delivered >= 5 {
3873 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3874 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3875 check_added_monitors!(nodes[0], 1);
3882 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3883 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3884 if messages_delivered < 2 {
3885 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3886 if messages_delivered < 1 {
3887 expect_payment_sent!(nodes[0], payment_preimage_1);
3889 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3891 } else if messages_delivered == 2 {
3892 // nodes[0] still wants its RAA + commitment_signed
3893 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3894 } else if messages_delivered == 3 {
3895 // nodes[0] still wants its commitment_signed
3896 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3897 } else if messages_delivered == 4 {
3898 // nodes[1] still wants its final RAA
3899 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3900 } else if messages_delivered == 5 {
3901 // Everything was delivered...
3902 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3905 if messages_delivered == 1 || messages_delivered == 2 {
3906 expect_payment_path_successful!(nodes[0]);
3908 if messages_delivered <= 5 {
3909 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3910 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3912 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3914 if messages_delivered > 2 {
3915 expect_payment_path_successful!(nodes[0]);
3918 // Channel should still work fine...
3919 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3920 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3921 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3925 fn test_drop_messages_peer_disconnect_a() {
3926 do_test_drop_messages_peer_disconnect(0, true);
3927 do_test_drop_messages_peer_disconnect(0, false);
3928 do_test_drop_messages_peer_disconnect(1, false);
3929 do_test_drop_messages_peer_disconnect(2, false);
3933 fn test_drop_messages_peer_disconnect_b() {
3934 do_test_drop_messages_peer_disconnect(3, false);
3935 do_test_drop_messages_peer_disconnect(4, false);
3936 do_test_drop_messages_peer_disconnect(5, false);
3937 do_test_drop_messages_peer_disconnect(6, false);
3941 fn test_channel_ready_without_best_block_updated() {
3942 // Previously, if we were offline when a funding transaction was locked in, and then we came
3943 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3944 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3945 // channel_ready immediately instead.
3946 let chanmon_cfgs = create_chanmon_cfgs(2);
3947 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3948 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3949 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3950 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3952 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3954 let conf_height = nodes[0].best_block_info().1 + 1;
3955 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3956 let block_txn = [funding_tx];
3957 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3958 let conf_block_header = nodes[0].get_block_header(conf_height);
3959 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3961 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3962 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3963 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3967 fn test_drop_messages_peer_disconnect_dual_htlc() {
3968 // Test that we can handle reconnecting when both sides of a channel have pending
3969 // commitment_updates when we disconnect.
3970 let chanmon_cfgs = create_chanmon_cfgs(2);
3971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3973 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3974 create_announced_chan_between_nodes(&nodes, 0, 1);
3976 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3978 // Now try to send a second payment which will fail to send
3979 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3980 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3981 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3982 check_added_monitors!(nodes[0], 1);
3984 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3985 assert_eq!(events_1.len(), 1);
3987 MessageSendEvent::UpdateHTLCs { .. } => {},
3988 _ => panic!("Unexpected event"),
3991 nodes[1].node.claim_funds(payment_preimage_1);
3992 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3993 check_added_monitors!(nodes[1], 1);
3995 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3996 assert_eq!(events_2.len(), 1);
3998 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
3999 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4000 assert!(update_add_htlcs.is_empty());
4001 assert_eq!(update_fulfill_htlcs.len(), 1);
4002 assert!(update_fail_htlcs.is_empty());
4003 assert!(update_fail_malformed_htlcs.is_empty());
4004 assert!(update_fee.is_none());
4006 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4007 let events_3 = nodes[0].node.get_and_clear_pending_events();
4008 assert_eq!(events_3.len(), 1);
4010 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4011 assert_eq!(*payment_preimage, payment_preimage_1);
4012 assert_eq!(*payment_hash, payment_hash_1);
4014 _ => panic!("Unexpected event"),
4017 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4018 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4019 // No commitment_signed so get_event_msg's assert(len == 1) passes
4020 check_added_monitors!(nodes[0], 1);
4022 _ => panic!("Unexpected event"),
4025 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4026 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4028 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
4029 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4030 assert_eq!(reestablish_1.len(), 1);
4031 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
4032 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4033 assert_eq!(reestablish_2.len(), 1);
4035 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4036 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4037 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4038 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4040 assert!(as_resp.0.is_none());
4041 assert!(bs_resp.0.is_none());
4043 assert!(bs_resp.1.is_none());
4044 assert!(bs_resp.2.is_none());
4046 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4048 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4049 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4050 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4051 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4052 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4053 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4054 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4055 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4056 // No commitment_signed so get_event_msg's assert(len == 1) passes
4057 check_added_monitors!(nodes[1], 1);
4059 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4060 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4061 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4062 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4063 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4064 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4065 assert!(bs_second_commitment_signed.update_fee.is_none());
4066 check_added_monitors!(nodes[1], 1);
4068 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4069 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4070 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4071 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4072 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4073 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4074 assert!(as_commitment_signed.update_fee.is_none());
4075 check_added_monitors!(nodes[0], 1);
4077 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4078 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4079 // No commitment_signed so get_event_msg's assert(len == 1) passes
4080 check_added_monitors!(nodes[0], 1);
4082 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4083 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4084 // No commitment_signed so get_event_msg's assert(len == 1) passes
4085 check_added_monitors!(nodes[1], 1);
4087 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4088 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4089 check_added_monitors!(nodes[1], 1);
4091 expect_pending_htlcs_forwardable!(nodes[1]);
4093 let events_5 = nodes[1].node.get_and_clear_pending_events();
4094 assert_eq!(events_5.len(), 1);
4096 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4097 assert_eq!(payment_hash_2, *payment_hash);
4099 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4100 assert!(payment_preimage.is_none());
4101 assert_eq!(payment_secret_2, *payment_secret);
4103 _ => panic!("expected PaymentPurpose::InvoicePayment")
4106 _ => panic!("Unexpected event"),
4109 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4110 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4111 check_added_monitors!(nodes[0], 1);
4113 expect_payment_path_successful!(nodes[0]);
4114 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4117 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4118 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4119 // to avoid our counterparty failing the channel.
4120 let chanmon_cfgs = create_chanmon_cfgs(2);
4121 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4122 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4123 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4125 create_announced_chan_between_nodes(&nodes, 0, 1);
4127 let our_payment_hash = if send_partial_mpp {
4128 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4129 // Use the utility function send_payment_along_path to send the payment with MPP data which
4130 // indicates there are more HTLCs coming.
4131 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4132 let payment_id = PaymentId([42; 32]);
4133 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4134 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4135 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4136 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4137 &None, session_privs[0]).unwrap();
4138 check_added_monitors!(nodes[0], 1);
4139 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4140 assert_eq!(events.len(), 1);
4141 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4142 // hop should *not* yet generate any PaymentClaimable event(s).
4143 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4146 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4149 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4150 connect_block(&nodes[0], &block);
4151 connect_block(&nodes[1], &block);
4152 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4153 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4154 block.header.prev_blockhash = block.block_hash();
4155 connect_block(&nodes[0], &block);
4156 connect_block(&nodes[1], &block);
4159 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4161 check_added_monitors!(nodes[1], 1);
4162 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4163 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4164 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4165 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4166 assert!(htlc_timeout_updates.update_fee.is_none());
4168 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4169 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4170 // 100_000 msat as u64, followed by the height at which we failed back above
4171 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4172 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4173 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4177 fn test_htlc_timeout() {
4178 do_test_htlc_timeout(true);
4179 do_test_htlc_timeout(false);
4182 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4183 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4184 let chanmon_cfgs = create_chanmon_cfgs(3);
4185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4187 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4188 create_announced_chan_between_nodes(&nodes, 0, 1);
4189 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4191 // Make sure all nodes are at the same starting height
4192 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4193 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4194 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4196 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4197 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4198 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4199 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4200 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4201 check_added_monitors!(nodes[1], 1);
4203 // Now attempt to route a second payment, which should be placed in the holding cell
4204 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4205 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4206 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4207 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4209 check_added_monitors!(nodes[0], 1);
4210 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4211 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4212 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4213 expect_pending_htlcs_forwardable!(nodes[1]);
4215 check_added_monitors!(nodes[1], 0);
4217 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4218 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4219 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4220 connect_blocks(&nodes[1], 1);
4223 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4224 check_added_monitors!(nodes[1], 1);
4225 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4226 assert_eq!(fail_commit.len(), 1);
4227 match fail_commit[0] {
4228 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4230 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4232 _ => unreachable!(),
4234 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4236 expect_payment_failed!(nodes[1], second_payment_hash, false);
4241 fn test_holding_cell_htlc_add_timeouts() {
4242 do_test_holding_cell_htlc_add_timeouts(false);
4243 do_test_holding_cell_htlc_add_timeouts(true);
4246 macro_rules! check_spendable_outputs {
4247 ($node: expr, $keysinterface: expr) => {
4249 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4250 let mut txn = Vec::new();
4251 let mut all_outputs = Vec::new();
4252 let secp_ctx = Secp256k1::new();
4253 for event in events.drain(..) {
4255 Event::SpendableOutputs { mut outputs } => {
4256 for outp in outputs.drain(..) {
4257 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4258 all_outputs.push(outp);
4261 _ => panic!("Unexpected event"),
4264 if all_outputs.len() > 1 {
4265 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx) {
4275 fn test_claim_sizeable_push_msat() {
4276 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4277 let chanmon_cfgs = create_chanmon_cfgs(2);
4278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4280 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4282 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4283 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4284 check_closed_broadcast!(nodes[1], true);
4285 check_added_monitors!(nodes[1], 1);
4286 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4287 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4288 assert_eq!(node_txn.len(), 1);
4289 check_spends!(node_txn[0], chan.3);
4290 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4292 mine_transaction(&nodes[1], &node_txn[0]);
4293 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4295 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4296 assert_eq!(spend_txn.len(), 1);
4297 assert_eq!(spend_txn[0].input.len(), 1);
4298 check_spends!(spend_txn[0], node_txn[0]);
4299 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4303 fn test_claim_on_remote_sizeable_push_msat() {
4304 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4305 // to_remote output is encumbered by a P2WPKH
4306 let chanmon_cfgs = create_chanmon_cfgs(2);
4307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4309 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4311 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4312 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4313 check_closed_broadcast!(nodes[0], true);
4314 check_added_monitors!(nodes[0], 1);
4315 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4317 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4318 assert_eq!(node_txn.len(), 1);
4319 check_spends!(node_txn[0], chan.3);
4320 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4322 mine_transaction(&nodes[1], &node_txn[0]);
4323 check_closed_broadcast!(nodes[1], true);
4324 check_added_monitors!(nodes[1], 1);
4325 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4326 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4328 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4329 assert_eq!(spend_txn.len(), 1);
4330 check_spends!(spend_txn[0], node_txn[0]);
4334 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4335 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4336 // to_remote output is encumbered by a P2WPKH
4338 let chanmon_cfgs = create_chanmon_cfgs(2);
4339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4341 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4343 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4344 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4345 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4346 assert_eq!(revoked_local_txn[0].input.len(), 1);
4347 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4349 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4350 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4351 check_closed_broadcast!(nodes[1], true);
4352 check_added_monitors!(nodes[1], 1);
4353 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4355 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4356 mine_transaction(&nodes[1], &node_txn[0]);
4357 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4359 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4360 assert_eq!(spend_txn.len(), 3);
4361 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4362 check_spends!(spend_txn[1], node_txn[0]);
4363 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4367 fn test_static_spendable_outputs_preimage_tx() {
4368 let chanmon_cfgs = create_chanmon_cfgs(2);
4369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4373 // Create some initial channels
4374 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4376 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4378 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4379 assert_eq!(commitment_tx[0].input.len(), 1);
4380 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4382 // Settle A's commitment tx on B's chain
4383 nodes[1].node.claim_funds(payment_preimage);
4384 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4385 check_added_monitors!(nodes[1], 1);
4386 mine_transaction(&nodes[1], &commitment_tx[0]);
4387 check_added_monitors!(nodes[1], 1);
4388 let events = nodes[1].node.get_and_clear_pending_msg_events();
4390 MessageSendEvent::UpdateHTLCs { .. } => {},
4391 _ => panic!("Unexpected event"),
4394 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4395 _ => panic!("Unexepected event"),
4398 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4399 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4400 assert_eq!(node_txn.len(), 1);
4401 check_spends!(node_txn[0], commitment_tx[0]);
4402 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4404 mine_transaction(&nodes[1], &node_txn[0]);
4405 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4406 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4408 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4409 assert_eq!(spend_txn.len(), 1);
4410 check_spends!(spend_txn[0], node_txn[0]);
4414 fn test_static_spendable_outputs_timeout_tx() {
4415 let chanmon_cfgs = create_chanmon_cfgs(2);
4416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4420 // Create some initial channels
4421 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4423 // Rebalance the network a bit by relaying one payment through all the channels ...
4424 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4426 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4428 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4429 assert_eq!(commitment_tx[0].input.len(), 1);
4430 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4432 // Settle A's commitment tx on B' chain
4433 mine_transaction(&nodes[1], &commitment_tx[0]);
4434 check_added_monitors!(nodes[1], 1);
4435 let events = nodes[1].node.get_and_clear_pending_msg_events();
4437 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4438 _ => panic!("Unexpected event"),
4440 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4442 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4443 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4444 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4445 check_spends!(node_txn[0], commitment_tx[0].clone());
4446 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4448 mine_transaction(&nodes[1], &node_txn[0]);
4449 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4450 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4451 expect_payment_failed!(nodes[1], our_payment_hash, false);
4453 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4454 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4455 check_spends!(spend_txn[0], commitment_tx[0]);
4456 check_spends!(spend_txn[1], node_txn[0]);
4457 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4461 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4462 let chanmon_cfgs = create_chanmon_cfgs(2);
4463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4467 // Create some initial channels
4468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4470 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4471 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4472 assert_eq!(revoked_local_txn[0].input.len(), 1);
4473 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4475 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4477 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4478 check_closed_broadcast!(nodes[1], true);
4479 check_added_monitors!(nodes[1], 1);
4480 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4482 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4483 assert_eq!(node_txn.len(), 1);
4484 assert_eq!(node_txn[0].input.len(), 2);
4485 check_spends!(node_txn[0], revoked_local_txn[0]);
4487 mine_transaction(&nodes[1], &node_txn[0]);
4488 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4490 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4491 assert_eq!(spend_txn.len(), 1);
4492 check_spends!(spend_txn[0], node_txn[0]);
4496 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4497 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4498 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4501 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4503 // Create some initial channels
4504 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4506 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4507 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4508 assert_eq!(revoked_local_txn[0].input.len(), 1);
4509 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4511 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4513 // A will generate HTLC-Timeout from revoked commitment tx
4514 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4515 check_closed_broadcast!(nodes[0], true);
4516 check_added_monitors!(nodes[0], 1);
4517 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4518 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4520 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4521 assert_eq!(revoked_htlc_txn.len(), 1);
4522 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4523 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4524 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4525 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4527 // B will generate justice tx from A's revoked commitment/HTLC tx
4528 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4529 check_closed_broadcast!(nodes[1], true);
4530 check_added_monitors!(nodes[1], 1);
4531 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4533 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4534 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4535 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4536 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4537 // transactions next...
4538 assert_eq!(node_txn[0].input.len(), 3);
4539 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4541 assert_eq!(node_txn[1].input.len(), 2);
4542 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4543 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4544 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4546 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4547 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4550 mine_transaction(&nodes[1], &node_txn[1]);
4551 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4553 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4554 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4555 assert_eq!(spend_txn.len(), 1);
4556 assert_eq!(spend_txn[0].input.len(), 1);
4557 check_spends!(spend_txn[0], node_txn[1]);
4561 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4562 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4563 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4564 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4565 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4566 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4568 // Create some initial channels
4569 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4571 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4572 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4573 assert_eq!(revoked_local_txn[0].input.len(), 1);
4574 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4576 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4577 assert_eq!(revoked_local_txn[0].output.len(), 2);
4579 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4581 // B will generate HTLC-Success from revoked commitment tx
4582 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4583 check_closed_broadcast!(nodes[1], true);
4584 check_added_monitors!(nodes[1], 1);
4585 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4586 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4588 assert_eq!(revoked_htlc_txn.len(), 1);
4589 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4590 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4591 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4593 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4594 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4595 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4597 // A will generate justice tx from B's revoked commitment/HTLC tx
4598 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4599 check_closed_broadcast!(nodes[0], true);
4600 check_added_monitors!(nodes[0], 1);
4601 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4603 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4606 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4607 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4608 // transactions next...
4609 assert_eq!(node_txn[0].input.len(), 2);
4610 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4611 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4612 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4614 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4615 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4618 assert_eq!(node_txn[1].input.len(), 1);
4619 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4621 mine_transaction(&nodes[0], &node_txn[1]);
4622 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4624 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4625 // didn't try to generate any new transactions.
4627 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4628 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4629 assert_eq!(spend_txn.len(), 3);
4630 assert_eq!(spend_txn[0].input.len(), 1);
4631 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4632 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4633 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4634 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4638 fn test_onchain_to_onchain_claim() {
4639 // Test that in case of channel closure, we detect the state of output and claim HTLC
4640 // on downstream peer's remote commitment tx.
4641 // First, have C claim an HTLC against its own latest commitment transaction.
4642 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4644 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4647 let chanmon_cfgs = create_chanmon_cfgs(3);
4648 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4649 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4650 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4652 // Create some initial channels
4653 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4654 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4656 // Ensure all nodes are at the same height
4657 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4658 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4659 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4660 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4662 // Rebalance the network a bit by relaying one payment through all the channels ...
4663 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4664 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4666 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4667 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4668 check_spends!(commitment_tx[0], chan_2.3);
4669 nodes[2].node.claim_funds(payment_preimage);
4670 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4671 check_added_monitors!(nodes[2], 1);
4672 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4673 assert!(updates.update_add_htlcs.is_empty());
4674 assert!(updates.update_fail_htlcs.is_empty());
4675 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4676 assert!(updates.update_fail_malformed_htlcs.is_empty());
4678 mine_transaction(&nodes[2], &commitment_tx[0]);
4679 check_closed_broadcast!(nodes[2], true);
4680 check_added_monitors!(nodes[2], 1);
4681 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4683 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4684 assert_eq!(c_txn.len(), 1);
4685 check_spends!(c_txn[0], commitment_tx[0]);
4686 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4687 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4688 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4690 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
4691 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4692 check_added_monitors!(nodes[1], 1);
4693 let events = nodes[1].node.get_and_clear_pending_events();
4694 assert_eq!(events.len(), 2);
4696 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4697 _ => panic!("Unexpected event"),
4700 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4701 assert_eq!(fee_earned_msat, Some(1000));
4702 assert_eq!(prev_channel_id, Some(chan_1.2));
4703 assert_eq!(claim_from_onchain_tx, true);
4704 assert_eq!(next_channel_id, Some(chan_2.2));
4705 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4707 _ => panic!("Unexpected event"),
4709 check_added_monitors!(nodes[1], 1);
4710 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4711 assert_eq!(msg_events.len(), 3);
4712 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4713 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4715 match nodes_2_event {
4716 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4717 _ => panic!("Unexpected event"),
4720 match nodes_0_event {
4721 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
4722 assert!(update_add_htlcs.is_empty());
4723 assert!(update_fail_htlcs.is_empty());
4724 assert_eq!(update_fulfill_htlcs.len(), 1);
4725 assert!(update_fail_malformed_htlcs.is_empty());
4726 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4728 _ => panic!("Unexpected event"),
4731 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4732 match msg_events[0] {
4733 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4734 _ => panic!("Unexpected event"),
4737 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4738 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4739 mine_transaction(&nodes[1], &commitment_tx[0]);
4740 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4741 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4742 // ChannelMonitor: HTLC-Success tx
4743 assert_eq!(b_txn.len(), 1);
4744 check_spends!(b_txn[0], commitment_tx[0]);
4745 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4746 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4747 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4749 check_closed_broadcast!(nodes[1], true);
4750 check_added_monitors!(nodes[1], 1);
4754 fn test_duplicate_payment_hash_one_failure_one_success() {
4755 // Topology : A --> B --> C --> D
4756 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4757 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4758 // we forward one of the payments onwards to D.
4759 let chanmon_cfgs = create_chanmon_cfgs(4);
4760 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4761 // When this test was written, the default base fee floated based on the HTLC count.
4762 // It is now fixed, so we simply set the fee to the expected value here.
4763 let mut config = test_default_channel_config();
4764 config.channel_config.forwarding_fee_base_msat = 196;
4765 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4766 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4767 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4769 create_announced_chan_between_nodes(&nodes, 0, 1);
4770 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4771 create_announced_chan_between_nodes(&nodes, 2, 3);
4773 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4774 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4775 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4776 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4777 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4779 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4781 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4782 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4783 // script push size limit so that the below script length checks match
4784 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4785 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4786 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4787 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4788 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4790 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4791 assert_eq!(commitment_txn[0].input.len(), 1);
4792 check_spends!(commitment_txn[0], chan_2.3);
4794 mine_transaction(&nodes[1], &commitment_txn[0]);
4795 check_closed_broadcast!(nodes[1], true);
4796 check_added_monitors!(nodes[1], 1);
4797 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4798 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4800 let htlc_timeout_tx;
4801 { // Extract one of the two HTLC-Timeout transaction
4802 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4803 // ChannelMonitor: timeout tx * 2-or-3
4804 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4806 check_spends!(node_txn[0], commitment_txn[0]);
4807 assert_eq!(node_txn[0].input.len(), 1);
4808 assert_eq!(node_txn[0].output.len(), 1);
4810 if node_txn.len() > 2 {
4811 check_spends!(node_txn[1], commitment_txn[0]);
4812 assert_eq!(node_txn[1].input.len(), 1);
4813 assert_eq!(node_txn[1].output.len(), 1);
4814 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4816 check_spends!(node_txn[2], commitment_txn[0]);
4817 assert_eq!(node_txn[2].input.len(), 1);
4818 assert_eq!(node_txn[2].output.len(), 1);
4819 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4821 check_spends!(node_txn[1], commitment_txn[0]);
4822 assert_eq!(node_txn[1].input.len(), 1);
4823 assert_eq!(node_txn[1].output.len(), 1);
4824 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4827 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4828 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4829 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4830 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4831 if node_txn.len() > 2 {
4832 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4835 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4839 nodes[2].node.claim_funds(our_payment_preimage);
4840 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4842 mine_transaction(&nodes[2], &commitment_txn[0]);
4843 check_added_monitors!(nodes[2], 2);
4844 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4845 let events = nodes[2].node.get_and_clear_pending_msg_events();
4847 MessageSendEvent::UpdateHTLCs { .. } => {},
4848 _ => panic!("Unexpected event"),
4851 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4852 _ => panic!("Unexepected event"),
4854 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4855 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4856 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4857 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4858 assert_eq!(htlc_success_txn[0].input.len(), 1);
4859 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4860 assert_eq!(htlc_success_txn[1].input.len(), 1);
4861 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4862 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4863 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4865 mine_transaction(&nodes[1], &htlc_timeout_tx);
4866 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4867 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4868 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4869 assert!(htlc_updates.update_add_htlcs.is_empty());
4870 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4871 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4872 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4873 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4874 check_added_monitors!(nodes[1], 1);
4876 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4877 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4879 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4881 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4883 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4884 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4885 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4886 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4887 assert!(updates.update_add_htlcs.is_empty());
4888 assert!(updates.update_fail_htlcs.is_empty());
4889 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4890 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4891 assert!(updates.update_fail_malformed_htlcs.is_empty());
4892 check_added_monitors!(nodes[1], 1);
4894 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4895 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4896 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4900 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4901 let chanmon_cfgs = create_chanmon_cfgs(2);
4902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906 // Create some initial channels
4907 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4909 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4910 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4911 assert_eq!(local_txn.len(), 1);
4912 assert_eq!(local_txn[0].input.len(), 1);
4913 check_spends!(local_txn[0], chan_1.3);
4915 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4916 nodes[1].node.claim_funds(payment_preimage);
4917 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4918 check_added_monitors!(nodes[1], 1);
4920 mine_transaction(&nodes[1], &local_txn[0]);
4921 check_added_monitors!(nodes[1], 1);
4922 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4923 let events = nodes[1].node.get_and_clear_pending_msg_events();
4925 MessageSendEvent::UpdateHTLCs { .. } => {},
4926 _ => panic!("Unexpected event"),
4929 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4930 _ => panic!("Unexepected event"),
4933 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4934 assert_eq!(node_txn.len(), 1);
4935 assert_eq!(node_txn[0].input.len(), 1);
4936 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4937 check_spends!(node_txn[0], local_txn[0]);
4941 mine_transaction(&nodes[1], &node_tx);
4942 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4944 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4945 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4946 assert_eq!(spend_txn.len(), 1);
4947 assert_eq!(spend_txn[0].input.len(), 1);
4948 check_spends!(spend_txn[0], node_tx);
4949 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4952 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4953 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4954 // unrevoked commitment transaction.
4955 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4956 // a remote RAA before they could be failed backwards (and combinations thereof).
4957 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4958 // use the same payment hashes.
4959 // Thus, we use a six-node network:
4964 // And test where C fails back to A/B when D announces its latest commitment transaction
4965 let chanmon_cfgs = create_chanmon_cfgs(6);
4966 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4967 // When this test was written, the default base fee floated based on the HTLC count.
4968 // It is now fixed, so we simply set the fee to the expected value here.
4969 let mut config = test_default_channel_config();
4970 config.channel_config.forwarding_fee_base_msat = 196;
4971 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4972 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4973 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4975 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4976 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4977 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4978 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4979 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4981 // Rebalance and check output sanity...
4982 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4983 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4984 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4986 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4987 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4989 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
4991 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
4992 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4994 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4996 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
4998 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5000 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5001 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5003 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
5005 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
5008 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5010 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5011 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5014 let (_, payment_hash_6, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5016 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5017 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
5019 // Double-check that six of the new HTLC were added
5020 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5021 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5022 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5023 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5025 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5026 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5027 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5028 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5029 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5030 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5031 check_added_monitors!(nodes[4], 0);
5033 let failed_destinations = vec![
5034 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5035 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5036 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5037 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5039 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5040 check_added_monitors!(nodes[4], 1);
5042 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5043 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5044 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5045 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5046 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5047 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5049 // Fail 3rd below-dust and 7th above-dust HTLCs
5050 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5051 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5052 check_added_monitors!(nodes[5], 0);
5054 let failed_destinations_2 = vec![
5055 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5056 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5058 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5059 check_added_monitors!(nodes[5], 1);
5061 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5062 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5063 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5064 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5066 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5068 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5069 let failed_destinations_3 = vec![
5070 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5071 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5072 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5073 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5074 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5075 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5077 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5078 check_added_monitors!(nodes[3], 1);
5079 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5080 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5081 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5082 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5083 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5084 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5085 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5086 if deliver_last_raa {
5087 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5089 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5092 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5093 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5094 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5095 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5097 // We now broadcast the latest commitment transaction, which *should* result in failures for
5098 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5099 // the non-broadcast above-dust HTLCs.
5101 // Alternatively, we may broadcast the previous commitment transaction, which should only
5102 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5103 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5105 if announce_latest {
5106 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5108 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5110 let events = nodes[2].node.get_and_clear_pending_events();
5111 let close_event = if deliver_last_raa {
5112 assert_eq!(events.len(), 2 + 6);
5113 events.last().clone().unwrap()
5115 assert_eq!(events.len(), 1);
5116 events.last().clone().unwrap()
5119 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5120 _ => panic!("Unexpected event"),
5123 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5124 check_closed_broadcast!(nodes[2], true);
5125 if deliver_last_raa {
5126 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5128 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5129 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5131 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5132 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5134 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5137 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5139 check_added_monitors!(nodes[2], 3);
5141 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5142 assert_eq!(cs_msgs.len(), 2);
5143 let mut a_done = false;
5144 for msg in cs_msgs {
5146 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5147 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5148 // should be failed-backwards here.
5149 let target = if *node_id == nodes[0].node.get_our_node_id() {
5150 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5151 for htlc in &updates.update_fail_htlcs {
5152 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5154 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5159 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5160 for htlc in &updates.update_fail_htlcs {
5161 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5163 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5164 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5167 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5168 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5169 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5170 if announce_latest {
5171 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5172 if *node_id == nodes[0].node.get_our_node_id() {
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5176 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5178 _ => panic!("Unexpected event"),
5182 let as_events = nodes[0].node.get_and_clear_pending_events();
5183 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5184 let mut as_failds = HashSet::new();
5185 let mut as_updates = 0;
5186 for event in as_events.iter() {
5187 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5188 assert!(as_failds.insert(*payment_hash));
5189 if *payment_hash != payment_hash_2 {
5190 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5192 assert!(!payment_failed_permanently);
5194 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5197 } else if let &Event::PaymentFailed { .. } = event {
5198 } else { panic!("Unexpected event"); }
5200 assert!(as_failds.contains(&payment_hash_1));
5201 assert!(as_failds.contains(&payment_hash_2));
5202 if announce_latest {
5203 assert!(as_failds.contains(&payment_hash_3));
5204 assert!(as_failds.contains(&payment_hash_5));
5206 assert!(as_failds.contains(&payment_hash_6));
5208 let bs_events = nodes[1].node.get_and_clear_pending_events();
5209 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5210 let mut bs_failds = HashSet::new();
5211 let mut bs_updates = 0;
5212 for event in bs_events.iter() {
5213 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5214 assert!(bs_failds.insert(*payment_hash));
5215 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5216 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5218 assert!(!payment_failed_permanently);
5220 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5223 } else if let &Event::PaymentFailed { .. } = event {
5224 } else { panic!("Unexpected event"); }
5226 assert!(bs_failds.contains(&payment_hash_1));
5227 assert!(bs_failds.contains(&payment_hash_2));
5228 if announce_latest {
5229 assert!(bs_failds.contains(&payment_hash_4));
5231 assert!(bs_failds.contains(&payment_hash_5));
5233 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5234 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5235 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5236 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5237 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5238 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5242 fn test_fail_backwards_latest_remote_announce_a() {
5243 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5247 fn test_fail_backwards_latest_remote_announce_b() {
5248 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5252 fn test_fail_backwards_previous_remote_announce() {
5253 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5254 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5255 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5259 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5260 let chanmon_cfgs = create_chanmon_cfgs(2);
5261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5263 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5265 // Create some initial channels
5266 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5268 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5269 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5270 assert_eq!(local_txn[0].input.len(), 1);
5271 check_spends!(local_txn[0], chan_1.3);
5273 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5274 mine_transaction(&nodes[0], &local_txn[0]);
5275 check_closed_broadcast!(nodes[0], true);
5276 check_added_monitors!(nodes[0], 1);
5277 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5278 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5280 let htlc_timeout = {
5281 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5282 assert_eq!(node_txn.len(), 1);
5283 assert_eq!(node_txn[0].input.len(), 1);
5284 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5285 check_spends!(node_txn[0], local_txn[0]);
5289 mine_transaction(&nodes[0], &htlc_timeout);
5290 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5291 expect_payment_failed!(nodes[0], our_payment_hash, false);
5293 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5294 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5295 assert_eq!(spend_txn.len(), 3);
5296 check_spends!(spend_txn[0], local_txn[0]);
5297 assert_eq!(spend_txn[1].input.len(), 1);
5298 check_spends!(spend_txn[1], htlc_timeout);
5299 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5300 assert_eq!(spend_txn[2].input.len(), 2);
5301 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5302 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5303 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5307 fn test_key_derivation_params() {
5308 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5309 // manager rotation to test that `channel_keys_id` returned in
5310 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5311 // then derive a `delayed_payment_key`.
5313 let chanmon_cfgs = create_chanmon_cfgs(3);
5315 // We manually create the node configuration to backup the seed.
5316 let seed = [42; 32];
5317 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5318 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5319 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5320 let scorer = Mutex::new(test_utils::TestScorer::new());
5321 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5322 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5323 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5324 node_cfgs.remove(0);
5325 node_cfgs.insert(0, node);
5327 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5328 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5330 // Create some initial channels
5331 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5333 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5334 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5335 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5337 // Ensure all nodes are at the same height
5338 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5339 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5340 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5341 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5343 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5344 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5345 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5346 assert_eq!(local_txn_1[0].input.len(), 1);
5347 check_spends!(local_txn_1[0], chan_1.3);
5349 // We check funding pubkey are unique
5350 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5351 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5352 if from_0_funding_key_0 == from_1_funding_key_0
5353 || from_0_funding_key_0 == from_1_funding_key_1
5354 || from_0_funding_key_1 == from_1_funding_key_0
5355 || from_0_funding_key_1 == from_1_funding_key_1 {
5356 panic!("Funding pubkeys aren't unique");
5359 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5360 mine_transaction(&nodes[0], &local_txn_1[0]);
5361 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5362 check_closed_broadcast!(nodes[0], true);
5363 check_added_monitors!(nodes[0], 1);
5364 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5366 let htlc_timeout = {
5367 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5368 assert_eq!(node_txn.len(), 1);
5369 assert_eq!(node_txn[0].input.len(), 1);
5370 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5371 check_spends!(node_txn[0], local_txn_1[0]);
5375 mine_transaction(&nodes[0], &htlc_timeout);
5376 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5377 expect_payment_failed!(nodes[0], our_payment_hash, false);
5379 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5380 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5381 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5382 assert_eq!(spend_txn.len(), 3);
5383 check_spends!(spend_txn[0], local_txn_1[0]);
5384 assert_eq!(spend_txn[1].input.len(), 1);
5385 check_spends!(spend_txn[1], htlc_timeout);
5386 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5387 assert_eq!(spend_txn[2].input.len(), 2);
5388 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5389 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5390 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5394 fn test_static_output_closing_tx() {
5395 let chanmon_cfgs = create_chanmon_cfgs(2);
5396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5400 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5402 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5403 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5405 mine_transaction(&nodes[0], &closing_tx);
5406 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5407 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5409 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5410 assert_eq!(spend_txn.len(), 1);
5411 check_spends!(spend_txn[0], closing_tx);
5413 mine_transaction(&nodes[1], &closing_tx);
5414 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5415 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5417 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5418 assert_eq!(spend_txn.len(), 1);
5419 check_spends!(spend_txn[0], closing_tx);
5422 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5423 let chanmon_cfgs = create_chanmon_cfgs(2);
5424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5426 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5427 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5429 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5431 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5432 // present in B's local commitment transaction, but none of A's commitment transactions.
5433 nodes[1].node.claim_funds(payment_preimage);
5434 check_added_monitors!(nodes[1], 1);
5435 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5437 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5438 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5439 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5441 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5442 check_added_monitors!(nodes[0], 1);
5443 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5444 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5445 check_added_monitors!(nodes[1], 1);
5447 let starting_block = nodes[1].best_block_info();
5448 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5449 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5450 connect_block(&nodes[1], &block);
5451 block.header.prev_blockhash = block.block_hash();
5453 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5454 check_closed_broadcast!(nodes[1], true);
5455 check_added_monitors!(nodes[1], 1);
5456 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5459 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5460 let chanmon_cfgs = create_chanmon_cfgs(2);
5461 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5462 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5463 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5464 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5466 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5467 nodes[0].node.send_payment_with_route(&route, payment_hash,
5468 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5469 check_added_monitors!(nodes[0], 1);
5471 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5473 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5474 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5475 // to "time out" the HTLC.
5477 let starting_block = nodes[1].best_block_info();
5478 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5480 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5481 connect_block(&nodes[0], &block);
5482 block.header.prev_blockhash = block.block_hash();
5484 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5485 check_closed_broadcast!(nodes[0], true);
5486 check_added_monitors!(nodes[0], 1);
5487 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5490 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5491 let chanmon_cfgs = create_chanmon_cfgs(3);
5492 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5493 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5494 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5495 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5497 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5498 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5499 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5500 // actually revoked.
5501 let htlc_value = if use_dust { 50000 } else { 3000000 };
5502 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5503 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5504 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5505 check_added_monitors!(nodes[1], 1);
5507 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5508 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5509 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5510 check_added_monitors!(nodes[0], 1);
5511 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5512 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5513 check_added_monitors!(nodes[1], 1);
5514 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5515 check_added_monitors!(nodes[1], 1);
5516 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5518 if check_revoke_no_close {
5519 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5520 check_added_monitors!(nodes[0], 1);
5523 let starting_block = nodes[1].best_block_info();
5524 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5525 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5526 connect_block(&nodes[0], &block);
5527 block.header.prev_blockhash = block.block_hash();
5529 if !check_revoke_no_close {
5530 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5531 check_closed_broadcast!(nodes[0], true);
5532 check_added_monitors!(nodes[0], 1);
5533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5535 expect_payment_failed!(nodes[0], our_payment_hash, true);
5539 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5540 // There are only a few cases to test here:
5541 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5542 // broadcastable commitment transactions result in channel closure,
5543 // * its included in an unrevoked-but-previous remote commitment transaction,
5544 // * its included in the latest remote or local commitment transactions.
5545 // We test each of the three possible commitment transactions individually and use both dust and
5547 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5548 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5549 // tested for at least one of the cases in other tests.
5551 fn htlc_claim_single_commitment_only_a() {
5552 do_htlc_claim_local_commitment_only(true);
5553 do_htlc_claim_local_commitment_only(false);
5555 do_htlc_claim_current_remote_commitment_only(true);
5556 do_htlc_claim_current_remote_commitment_only(false);
5560 fn htlc_claim_single_commitment_only_b() {
5561 do_htlc_claim_previous_remote_commitment_only(true, false);
5562 do_htlc_claim_previous_remote_commitment_only(false, false);
5563 do_htlc_claim_previous_remote_commitment_only(true, true);
5564 do_htlc_claim_previous_remote_commitment_only(false, true);
5569 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5570 let chanmon_cfgs = create_chanmon_cfgs(2);
5571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5574 // Force duplicate randomness for every get-random call
5575 for node in nodes.iter() {
5576 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5579 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5580 let channel_value_satoshis=10000;
5581 let push_msat=10001;
5582 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5583 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5584 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5585 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5587 // Create a second channel with the same random values. This used to panic due to a colliding
5588 // channel_id, but now panics due to a colliding outbound SCID alias.
5589 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5593 fn bolt2_open_channel_sending_node_checks_part2() {
5594 let chanmon_cfgs = create_chanmon_cfgs(2);
5595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5597 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5599 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5600 let channel_value_satoshis=2^24;
5601 let push_msat=10001;
5602 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5604 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5605 let channel_value_satoshis=10000;
5606 // Test when push_msat is equal to 1000 * funding_satoshis.
5607 let push_msat=1000*channel_value_satoshis+1;
5608 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5610 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5611 let channel_value_satoshis=10000;
5612 let push_msat=10001;
5613 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5614 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5615 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5617 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5618 // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5619 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5621 // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5622 assert!(BREAKDOWN_TIMEOUT>0);
5623 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5625 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5626 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5627 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5629 // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5630 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5631 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5632 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5633 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5634 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5638 fn bolt2_open_channel_sane_dust_limit() {
5639 let chanmon_cfgs = create_chanmon_cfgs(2);
5640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5644 let channel_value_satoshis=1000000;
5645 let push_msat=10001;
5646 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5647 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5648 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5649 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5651 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5652 let events = nodes[1].node.get_and_clear_pending_msg_events();
5653 let err_msg = match events[0] {
5654 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5657 _ => panic!("Unexpected event"),
5659 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5662 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5663 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5664 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5665 // is no longer affordable once it's freed.
5667 fn test_fail_holding_cell_htlc_upon_free() {
5668 let chanmon_cfgs = create_chanmon_cfgs(2);
5669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5672 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5674 // First nodes[0] generates an update_fee, setting the channel's
5675 // pending_update_fee.
5677 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5678 *feerate_lock += 20;
5680 nodes[0].node.timer_tick_occurred();
5681 check_added_monitors!(nodes[0], 1);
5683 let events = nodes[0].node.get_and_clear_pending_msg_events();
5684 assert_eq!(events.len(), 1);
5685 let (update_msg, commitment_signed) = match events[0] {
5686 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5687 (update_fee.as_ref(), commitment_signed)
5689 _ => panic!("Unexpected event"),
5692 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5694 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5695 let channel_reserve = chan_stat.channel_reserve_msat;
5696 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5697 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5699 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5700 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5701 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5703 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5704 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5705 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5706 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5707 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5709 // Flush the pending fee update.
5710 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5711 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5712 check_added_monitors!(nodes[1], 1);
5713 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5714 check_added_monitors!(nodes[0], 1);
5716 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5717 // HTLC, but now that the fee has been raised the payment will now fail, causing
5718 // us to surface its failure to the user.
5719 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5720 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5721 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5722 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5723 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5724 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5726 // Check that the payment failed to be sent out.
5727 let events = nodes[0].node.get_and_clear_pending_events();
5728 assert_eq!(events.len(), 2);
5730 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5731 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5732 assert_eq!(our_payment_hash.clone(), *payment_hash);
5733 assert_eq!(*payment_failed_permanently, false);
5734 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5736 _ => panic!("Unexpected event"),
5739 &Event::PaymentFailed { ref payment_hash, .. } => {
5740 assert_eq!(our_payment_hash.clone(), *payment_hash);
5742 _ => panic!("Unexpected event"),
5746 // Test that if multiple HTLCs are released from the holding cell and one is
5747 // valid but the other is no longer valid upon release, the valid HTLC can be
5748 // successfully completed while the other one fails as expected.
5750 fn test_free_and_fail_holding_cell_htlcs() {
5751 let chanmon_cfgs = create_chanmon_cfgs(2);
5752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5757 // First nodes[0] generates an update_fee, setting the channel's
5758 // pending_update_fee.
5760 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5761 *feerate_lock += 200;
5763 nodes[0].node.timer_tick_occurred();
5764 check_added_monitors!(nodes[0], 1);
5766 let events = nodes[0].node.get_and_clear_pending_msg_events();
5767 assert_eq!(events.len(), 1);
5768 let (update_msg, commitment_signed) = match events[0] {
5769 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5770 (update_fee.as_ref(), commitment_signed)
5772 _ => panic!("Unexpected event"),
5775 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5777 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5778 let channel_reserve = chan_stat.channel_reserve_msat;
5779 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5780 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5782 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5784 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5785 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5786 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5788 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5789 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5790 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5791 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5792 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5793 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5794 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5795 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5796 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5797 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5799 // Flush the pending fee update.
5800 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5801 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5802 check_added_monitors!(nodes[1], 1);
5803 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5804 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5805 check_added_monitors!(nodes[0], 2);
5807 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5808 // but now that the fee has been raised the second payment will now fail, causing us
5809 // to surface its failure to the user. The first payment should succeed.
5810 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5811 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5812 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 2 HTLC updates in channel {}", hex::encode(chan.2)), 1);
5813 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5814 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5815 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5817 // Check that the second payment failed to be sent out.
5818 let events = nodes[0].node.get_and_clear_pending_events();
5819 assert_eq!(events.len(), 2);
5821 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5822 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5823 assert_eq!(payment_hash_2.clone(), *payment_hash);
5824 assert_eq!(*payment_failed_permanently, false);
5825 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5827 _ => panic!("Unexpected event"),
5830 &Event::PaymentFailed { ref payment_hash, .. } => {
5831 assert_eq!(payment_hash_2.clone(), *payment_hash);
5833 _ => panic!("Unexpected event"),
5836 // Complete the first payment and the RAA from the fee update.
5837 let (payment_event, send_raa_event) = {
5838 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5839 assert_eq!(msgs.len(), 2);
5840 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5842 let raa = match send_raa_event {
5843 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5844 _ => panic!("Unexpected event"),
5846 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5847 check_added_monitors!(nodes[1], 1);
5848 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5849 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5850 let events = nodes[1].node.get_and_clear_pending_events();
5851 assert_eq!(events.len(), 1);
5853 Event::PendingHTLCsForwardable { .. } => {},
5854 _ => panic!("Unexpected event"),
5856 nodes[1].node.process_pending_htlc_forwards();
5857 let events = nodes[1].node.get_and_clear_pending_events();
5858 assert_eq!(events.len(), 1);
5860 Event::PaymentClaimable { .. } => {},
5861 _ => panic!("Unexpected event"),
5863 nodes[1].node.claim_funds(payment_preimage_1);
5864 check_added_monitors!(nodes[1], 1);
5865 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5867 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5868 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5869 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5870 expect_payment_sent!(nodes[0], payment_preimage_1);
5873 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5874 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5875 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5878 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5879 let chanmon_cfgs = create_chanmon_cfgs(3);
5880 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5881 // Avoid having to include routing fees in calculations
5882 let mut config = test_default_channel_config();
5883 config.channel_config.forwarding_fee_base_msat = 0;
5884 config.channel_config.forwarding_fee_proportional_millionths = 0;
5885 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5886 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5887 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5888 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5890 // First nodes[1] generates an update_fee, setting the channel's
5891 // pending_update_fee.
5893 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5894 *feerate_lock += 20;
5896 nodes[1].node.timer_tick_occurred();
5897 check_added_monitors!(nodes[1], 1);
5899 let events = nodes[1].node.get_and_clear_pending_msg_events();
5900 assert_eq!(events.len(), 1);
5901 let (update_msg, commitment_signed) = match events[0] {
5902 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5903 (update_fee.as_ref(), commitment_signed)
5905 _ => panic!("Unexpected event"),
5908 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5910 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5911 let channel_reserve = chan_stat.channel_reserve_msat;
5912 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5913 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5915 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5916 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5917 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5918 let payment_event = {
5919 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5920 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5921 check_added_monitors!(nodes[0], 1);
5923 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5924 assert_eq!(events.len(), 1);
5926 SendEvent::from_event(events.remove(0))
5928 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5929 check_added_monitors!(nodes[1], 0);
5930 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5931 expect_pending_htlcs_forwardable!(nodes[1]);
5933 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5934 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5936 // Flush the pending fee update.
5937 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5938 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5939 check_added_monitors!(nodes[2], 1);
5940 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5941 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5942 check_added_monitors!(nodes[1], 2);
5944 // A final RAA message is generated to finalize the fee update.
5945 let events = nodes[1].node.get_and_clear_pending_msg_events();
5946 assert_eq!(events.len(), 1);
5948 let raa_msg = match &events[0] {
5949 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5952 _ => panic!("Unexpected event"),
5955 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5956 check_added_monitors!(nodes[2], 1);
5957 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5959 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5960 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5961 assert_eq!(process_htlc_forwards_event.len(), 2);
5962 match &process_htlc_forwards_event[0] {
5963 &Event::PendingHTLCsForwardable { .. } => {},
5964 _ => panic!("Unexpected event"),
5967 // In response, we call ChannelManager's process_pending_htlc_forwards
5968 nodes[1].node.process_pending_htlc_forwards();
5969 check_added_monitors!(nodes[1], 1);
5971 // This causes the HTLC to be failed backwards.
5972 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5973 assert_eq!(fail_event.len(), 1);
5974 let (fail_msg, commitment_signed) = match &fail_event[0] {
5975 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5976 assert_eq!(updates.update_add_htlcs.len(), 0);
5977 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5978 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5979 assert_eq!(updates.update_fail_htlcs.len(), 1);
5980 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5982 _ => panic!("Unexpected event"),
5985 // Pass the failure messages back to nodes[0].
5986 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5989 // Complete the HTLC failure+removal process.
5990 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5991 check_added_monitors!(nodes[0], 1);
5992 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5993 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5994 check_added_monitors!(nodes[1], 2);
5995 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5996 assert_eq!(final_raa_event.len(), 1);
5997 let raa = match &final_raa_event[0] {
5998 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5999 _ => panic!("Unexpected event"),
6001 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6002 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6003 check_added_monitors!(nodes[0], 1);
6006 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6007 // 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.
6008 //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.
6011 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6012 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6013 let chanmon_cfgs = create_chanmon_cfgs(2);
6014 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6015 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6016 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6017 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6019 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6020 route.paths[0].hops[0].fee_msat = 100;
6022 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6023 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6024 ), true, APIError::ChannelUnavailable { ref err },
6025 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6026 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6027 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6031 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6032 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6033 let chanmon_cfgs = create_chanmon_cfgs(2);
6034 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6035 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6036 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6037 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6039 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6040 route.paths[0].hops[0].fee_msat = 0;
6041 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6042 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6043 true, APIError::ChannelUnavailable { ref err },
6044 assert_eq!(err, "Cannot send 0-msat HTLC"));
6046 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6047 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6051 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6052 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6053 let chanmon_cfgs = create_chanmon_cfgs(2);
6054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6056 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6057 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6059 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6060 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6061 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6062 check_added_monitors!(nodes[0], 1);
6063 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6064 updates.update_add_htlcs[0].amount_msat = 0;
6066 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6067 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6068 check_closed_broadcast!(nodes[1], true).unwrap();
6069 check_added_monitors!(nodes[1], 1);
6070 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6074 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6075 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6076 //It is enforced when constructing a route.
6077 let chanmon_cfgs = create_chanmon_cfgs(2);
6078 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6079 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6080 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6081 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6083 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6084 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6085 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6086 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6087 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6088 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6089 ), true, APIError::InvalidRoute { ref err },
6090 assert_eq!(err, &"Channel CLTV overflowed?"));
6094 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6095 //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.
6096 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6097 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6098 let chanmon_cfgs = create_chanmon_cfgs(2);
6099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6101 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6102 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6103 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6104 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6106 for i in 0..max_accepted_htlcs {
6107 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6108 let payment_event = {
6109 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6110 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6111 check_added_monitors!(nodes[0], 1);
6113 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6114 assert_eq!(events.len(), 1);
6115 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6116 assert_eq!(htlcs[0].htlc_id, i);
6120 SendEvent::from_event(events.remove(0))
6122 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6123 check_added_monitors!(nodes[1], 0);
6124 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6126 expect_pending_htlcs_forwardable!(nodes[1]);
6127 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6129 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6130 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6131 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6132 ), true, APIError::ChannelUnavailable { ref err },
6133 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6135 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6136 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6140 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6141 //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.
6142 let chanmon_cfgs = create_chanmon_cfgs(2);
6143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6145 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6146 let channel_value = 100000;
6147 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6148 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6150 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6152 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6153 // Manually create a route over our max in flight (which our router normally automatically
6155 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6156 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6157 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6158 ), true, APIError::ChannelUnavailable { ref err },
6159 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)));
6161 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6162 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);
6164 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6167 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6169 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6170 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6171 let chanmon_cfgs = create_chanmon_cfgs(2);
6172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6174 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6175 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6176 let htlc_minimum_msat: u64;
6178 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6179 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6180 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6181 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6184 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6185 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6186 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6187 check_added_monitors!(nodes[0], 1);
6188 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6189 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6190 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6191 assert!(nodes[1].node.list_channels().is_empty());
6192 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6193 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()));
6194 check_added_monitors!(nodes[1], 1);
6195 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6199 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6200 //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
6201 let chanmon_cfgs = create_chanmon_cfgs(2);
6202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6204 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6205 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6207 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6208 let channel_reserve = chan_stat.channel_reserve_msat;
6209 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6210 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6211 // The 2* and +1 are for the fee spike reserve.
6212 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6214 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6215 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6216 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6217 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6218 check_added_monitors!(nodes[0], 1);
6219 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6221 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6222 // at this time channel-initiatee receivers are not required to enforce that senders
6223 // respect the fee_spike_reserve.
6224 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6225 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6227 assert!(nodes[1].node.list_channels().is_empty());
6228 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6229 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6230 check_added_monitors!(nodes[1], 1);
6231 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6235 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6236 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6237 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6238 let chanmon_cfgs = create_chanmon_cfgs(2);
6239 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6240 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6241 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6242 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6244 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6245 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6246 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6247 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6248 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6249 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6250 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6252 let mut msg = msgs::UpdateAddHTLC {
6256 payment_hash: our_payment_hash,
6257 cltv_expiry: htlc_cltv,
6258 onion_routing_packet: onion_packet.clone(),
6262 msg.htlc_id = i as u64;
6263 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6265 msg.htlc_id = (50) as u64;
6266 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6268 assert!(nodes[1].node.list_channels().is_empty());
6269 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6270 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6271 check_added_monitors!(nodes[1], 1);
6272 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6276 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6277 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6278 let chanmon_cfgs = create_chanmon_cfgs(2);
6279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6281 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6282 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6284 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6285 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6286 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6287 check_added_monitors!(nodes[0], 1);
6288 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6289 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;
6290 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6292 assert!(nodes[1].node.list_channels().is_empty());
6293 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6294 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6295 check_added_monitors!(nodes[1], 1);
6296 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6300 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6301 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6302 let chanmon_cfgs = create_chanmon_cfgs(2);
6303 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6304 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6305 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6307 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6308 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6309 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6310 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6311 check_added_monitors!(nodes[0], 1);
6312 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6313 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6314 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6316 assert!(nodes[1].node.list_channels().is_empty());
6317 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6318 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6319 check_added_monitors!(nodes[1], 1);
6320 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6324 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6325 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6326 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6327 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6328 let chanmon_cfgs = create_chanmon_cfgs(2);
6329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6331 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6333 create_announced_chan_between_nodes(&nodes, 0, 1);
6334 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6335 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6336 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6337 check_added_monitors!(nodes[0], 1);
6338 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6339 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6341 //Disconnect and Reconnect
6342 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6343 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6344 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();
6345 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6346 assert_eq!(reestablish_1.len(), 1);
6347 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();
6348 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6349 assert_eq!(reestablish_2.len(), 1);
6350 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6351 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6352 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6353 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6356 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6357 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6358 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6359 check_added_monitors!(nodes[1], 1);
6360 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6362 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6364 assert!(nodes[1].node.list_channels().is_empty());
6365 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6366 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6367 check_added_monitors!(nodes[1], 1);
6368 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6372 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6373 //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.
6375 let chanmon_cfgs = create_chanmon_cfgs(2);
6376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6378 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6379 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6380 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6381 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6382 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6384 check_added_monitors!(nodes[0], 1);
6385 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6386 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6388 let update_msg = msgs::UpdateFulfillHTLC{
6391 payment_preimage: our_payment_preimage,
6394 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6396 assert!(nodes[0].node.list_channels().is_empty());
6397 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6398 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()));
6399 check_added_monitors!(nodes[0], 1);
6400 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6404 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6405 //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.
6407 let chanmon_cfgs = create_chanmon_cfgs(2);
6408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6410 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6411 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6413 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6414 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6415 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6416 check_added_monitors!(nodes[0], 1);
6417 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6418 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6420 let update_msg = msgs::UpdateFailHTLC{
6423 reason: msgs::OnionErrorPacket { data: Vec::new()},
6426 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6428 assert!(nodes[0].node.list_channels().is_empty());
6429 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6430 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()));
6431 check_added_monitors!(nodes[0], 1);
6432 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6436 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6437 //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.
6439 let chanmon_cfgs = create_chanmon_cfgs(2);
6440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6442 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6443 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6445 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6446 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6447 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6448 check_added_monitors!(nodes[0], 1);
6449 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6450 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6451 let update_msg = msgs::UpdateFailMalformedHTLC{
6454 sha256_of_onion: [1; 32],
6455 failure_code: 0x8000,
6458 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6460 assert!(nodes[0].node.list_channels().is_empty());
6461 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6462 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()));
6463 check_added_monitors!(nodes[0], 1);
6464 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6468 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6469 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6471 let chanmon_cfgs = create_chanmon_cfgs(2);
6472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6475 create_announced_chan_between_nodes(&nodes, 0, 1);
6477 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6479 nodes[1].node.claim_funds(our_payment_preimage);
6480 check_added_monitors!(nodes[1], 1);
6481 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6483 let events = nodes[1].node.get_and_clear_pending_msg_events();
6484 assert_eq!(events.len(), 1);
6485 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6487 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, .. } } => {
6488 assert!(update_add_htlcs.is_empty());
6489 assert_eq!(update_fulfill_htlcs.len(), 1);
6490 assert!(update_fail_htlcs.is_empty());
6491 assert!(update_fail_malformed_htlcs.is_empty());
6492 assert!(update_fee.is_none());
6493 update_fulfill_htlcs[0].clone()
6495 _ => panic!("Unexpected event"),
6499 update_fulfill_msg.htlc_id = 1;
6501 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6503 assert!(nodes[0].node.list_channels().is_empty());
6504 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6505 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6506 check_added_monitors!(nodes[0], 1);
6507 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6511 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6512 //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.
6514 let chanmon_cfgs = create_chanmon_cfgs(2);
6515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6518 create_announced_chan_between_nodes(&nodes, 0, 1);
6520 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6522 nodes[1].node.claim_funds(our_payment_preimage);
6523 check_added_monitors!(nodes[1], 1);
6524 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6526 let events = nodes[1].node.get_and_clear_pending_msg_events();
6527 assert_eq!(events.len(), 1);
6528 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6530 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, .. } } => {
6531 assert!(update_add_htlcs.is_empty());
6532 assert_eq!(update_fulfill_htlcs.len(), 1);
6533 assert!(update_fail_htlcs.is_empty());
6534 assert!(update_fail_malformed_htlcs.is_empty());
6535 assert!(update_fee.is_none());
6536 update_fulfill_htlcs[0].clone()
6538 _ => panic!("Unexpected event"),
6542 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6544 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6546 assert!(nodes[0].node.list_channels().is_empty());
6547 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6548 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6549 check_added_monitors!(nodes[0], 1);
6550 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6554 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6555 //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.
6557 let chanmon_cfgs = create_chanmon_cfgs(2);
6558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6560 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6561 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6563 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6564 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6565 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6566 check_added_monitors!(nodes[0], 1);
6568 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6569 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6571 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6572 check_added_monitors!(nodes[1], 0);
6573 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6575 let events = nodes[1].node.get_and_clear_pending_msg_events();
6577 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6579 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, .. } } => {
6580 assert!(update_add_htlcs.is_empty());
6581 assert!(update_fulfill_htlcs.is_empty());
6582 assert!(update_fail_htlcs.is_empty());
6583 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6584 assert!(update_fee.is_none());
6585 update_fail_malformed_htlcs[0].clone()
6587 _ => panic!("Unexpected event"),
6590 update_msg.failure_code &= !0x8000;
6591 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6593 assert!(nodes[0].node.list_channels().is_empty());
6594 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6595 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6596 check_added_monitors!(nodes[0], 1);
6597 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6601 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6602 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6603 // * 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.
6605 let chanmon_cfgs = create_chanmon_cfgs(3);
6606 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6607 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6608 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6609 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6610 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6612 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6615 let mut payment_event = {
6616 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6617 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6618 check_added_monitors!(nodes[0], 1);
6619 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6620 assert_eq!(events.len(), 1);
6621 SendEvent::from_event(events.remove(0))
6623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6624 check_added_monitors!(nodes[1], 0);
6625 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6626 expect_pending_htlcs_forwardable!(nodes[1]);
6627 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6628 assert_eq!(events_2.len(), 1);
6629 check_added_monitors!(nodes[1], 1);
6630 payment_event = SendEvent::from_event(events_2.remove(0));
6631 assert_eq!(payment_event.msgs.len(), 1);
6634 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6635 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6636 check_added_monitors!(nodes[2], 0);
6637 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6639 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6640 assert_eq!(events_3.len(), 1);
6641 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6643 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 } } => {
6644 assert!(update_add_htlcs.is_empty());
6645 assert!(update_fulfill_htlcs.is_empty());
6646 assert!(update_fail_htlcs.is_empty());
6647 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6648 assert!(update_fee.is_none());
6649 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6651 _ => panic!("Unexpected event"),
6655 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6657 check_added_monitors!(nodes[1], 0);
6658 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6659 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 }]);
6660 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6661 assert_eq!(events_4.len(), 1);
6663 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6665 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, .. } } => {
6666 assert!(update_add_htlcs.is_empty());
6667 assert!(update_fulfill_htlcs.is_empty());
6668 assert_eq!(update_fail_htlcs.len(), 1);
6669 assert!(update_fail_malformed_htlcs.is_empty());
6670 assert!(update_fee.is_none());
6672 _ => panic!("Unexpected event"),
6675 check_added_monitors!(nodes[1], 1);
6679 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6680 let chanmon_cfgs = create_chanmon_cfgs(3);
6681 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6682 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6683 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6684 create_announced_chan_between_nodes(&nodes, 0, 1);
6685 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6687 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6690 let mut payment_event = {
6691 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6692 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6693 check_added_monitors!(nodes[0], 1);
6694 SendEvent::from_node(&nodes[0])
6697 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6698 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6699 expect_pending_htlcs_forwardable!(nodes[1]);
6700 check_added_monitors!(nodes[1], 1);
6701 payment_event = SendEvent::from_node(&nodes[1]);
6702 assert_eq!(payment_event.msgs.len(), 1);
6705 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6706 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6707 check_added_monitors!(nodes[2], 0);
6708 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6710 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6711 assert_eq!(events_3.len(), 1);
6713 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6714 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6715 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6716 update_msg.failure_code |= 0x2000;
6718 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6719 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6721 _ => panic!("Unexpected event"),
6724 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6725 vec![HTLCDestination::NextHopChannel {
6726 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6727 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6728 assert_eq!(events_4.len(), 1);
6729 check_added_monitors!(nodes[1], 1);
6732 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6733 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6734 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6736 _ => panic!("Unexpected event"),
6739 let events_5 = nodes[0].node.get_and_clear_pending_events();
6740 assert_eq!(events_5.len(), 2);
6742 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6743 // the node originating the error to its next hop.
6745 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6747 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6748 assert!(is_permanent);
6749 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6751 _ => panic!("Unexpected event"),
6754 Event::PaymentFailed { payment_hash, .. } => {
6755 assert_eq!(payment_hash, our_payment_hash);
6757 _ => panic!("Unexpected event"),
6760 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6763 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6764 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6765 // 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
6766 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6768 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6769 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6772 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6773 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6775 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6776 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6778 // We route 2 dust-HTLCs between A and B
6779 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6780 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6781 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6783 // Cache one local commitment tx as previous
6784 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6786 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6787 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6788 check_added_monitors!(nodes[1], 0);
6789 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6790 check_added_monitors!(nodes[1], 1);
6792 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6793 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6794 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6795 check_added_monitors!(nodes[0], 1);
6797 // Cache one local commitment tx as lastest
6798 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6800 let events = nodes[0].node.get_and_clear_pending_msg_events();
6802 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6803 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6805 _ => panic!("Unexpected event"),
6808 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6809 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6811 _ => panic!("Unexpected event"),
6814 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6815 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6816 if announce_latest {
6817 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6819 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6822 check_closed_broadcast!(nodes[0], true);
6823 check_added_monitors!(nodes[0], 1);
6824 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6826 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6827 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6828 let events = nodes[0].node.get_and_clear_pending_events();
6829 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6830 assert_eq!(events.len(), 4);
6831 let mut first_failed = false;
6832 for event in events {
6834 Event::PaymentPathFailed { payment_hash, .. } => {
6835 if payment_hash == payment_hash_1 {
6836 assert!(!first_failed);
6837 first_failed = true;
6839 assert_eq!(payment_hash, payment_hash_2);
6842 Event::PaymentFailed { .. } => {}
6843 _ => panic!("Unexpected event"),
6849 fn test_failure_delay_dust_htlc_local_commitment() {
6850 do_test_failure_delay_dust_htlc_local_commitment(true);
6851 do_test_failure_delay_dust_htlc_local_commitment(false);
6854 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6855 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6856 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6857 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6858 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6859 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6860 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6862 let chanmon_cfgs = create_chanmon_cfgs(3);
6863 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6864 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6865 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6866 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6868 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6869 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6871 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6872 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6874 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6875 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6877 // We revoked bs_commitment_tx
6879 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6880 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6883 let mut timeout_tx = Vec::new();
6885 // We fail dust-HTLC 1 by broadcast of local commitment tx
6886 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6887 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6888 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6889 expect_payment_failed!(nodes[0], dust_hash, false);
6891 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6892 check_closed_broadcast!(nodes[0], true);
6893 check_added_monitors!(nodes[0], 1);
6894 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6895 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6896 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6897 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6898 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6899 mine_transaction(&nodes[0], &timeout_tx[0]);
6900 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6901 expect_payment_failed!(nodes[0], non_dust_hash, false);
6903 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6904 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6905 check_closed_broadcast!(nodes[0], true);
6906 check_added_monitors!(nodes[0], 1);
6907 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6908 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6910 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6911 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6912 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6913 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6914 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6915 // dust HTLC should have been failed.
6916 expect_payment_failed!(nodes[0], dust_hash, false);
6919 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6921 assert_eq!(timeout_tx[0].lock_time.0, 11);
6923 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6924 mine_transaction(&nodes[0], &timeout_tx[0]);
6925 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6926 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6927 expect_payment_failed!(nodes[0], non_dust_hash, false);
6932 fn test_sweep_outbound_htlc_failure_update() {
6933 do_test_sweep_outbound_htlc_failure_update(false, true);
6934 do_test_sweep_outbound_htlc_failure_update(false, false);
6935 do_test_sweep_outbound_htlc_failure_update(true, false);
6939 fn test_user_configurable_csv_delay() {
6940 // We test our channel constructors yield errors when we pass them absurd csv delay
6942 let mut low_our_to_self_config = UserConfig::default();
6943 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6944 let mut high_their_to_self_config = UserConfig::default();
6945 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6946 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6947 let chanmon_cfgs = create_chanmon_cfgs(2);
6948 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6949 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6950 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6952 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6953 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6954 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6955 &low_our_to_self_config, 0, 42)
6958 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())); },
6959 _ => panic!("Unexpected event"),
6961 } else { assert!(false) }
6963 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6964 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6965 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6966 open_channel.to_self_delay = 200;
6967 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6968 &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,
6969 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6972 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())); },
6973 _ => panic!("Unexpected event"),
6975 } else { assert!(false); }
6977 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6978 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6979 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()));
6980 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6981 accept_channel.to_self_delay = 200;
6982 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6984 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6986 &ErrorAction::SendErrorMessage { ref msg } => {
6987 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()));
6988 reason_msg = msg.data.clone();
6992 } else { panic!(); }
6993 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6995 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6996 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6997 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6998 open_channel.to_self_delay = 200;
6999 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7000 &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,
7001 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7004 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())); },
7005 _ => panic!("Unexpected event"),
7007 } else { assert!(false); }
7011 fn test_check_htlc_underpaying() {
7012 // Send payment through A -> B but A is maliciously
7013 // sending a probe payment (i.e less than expected value0
7014 // to B, B should refuse payment.
7016 let chanmon_cfgs = create_chanmon_cfgs(2);
7017 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7018 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7019 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7021 // Create some initial channels
7022 create_announced_chan_between_nodes(&nodes, 0, 1);
7024 let scorer = test_utils::TestScorer::new();
7025 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7026 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();
7027 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();
7028 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7029 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7030 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7031 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7032 check_added_monitors!(nodes[0], 1);
7034 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7035 assert_eq!(events.len(), 1);
7036 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7037 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7038 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7040 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7041 // and then will wait a second random delay before failing the HTLC back:
7042 expect_pending_htlcs_forwardable!(nodes[1]);
7043 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7045 // Node 3 is expecting payment of 100_000 but received 10_000,
7046 // it should fail htlc like we didn't know the preimage.
7047 nodes[1].node.process_pending_htlc_forwards();
7049 let events = nodes[1].node.get_and_clear_pending_msg_events();
7050 assert_eq!(events.len(), 1);
7051 let (update_fail_htlc, commitment_signed) = match events[0] {
7052 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 } } => {
7053 assert!(update_add_htlcs.is_empty());
7054 assert!(update_fulfill_htlcs.is_empty());
7055 assert_eq!(update_fail_htlcs.len(), 1);
7056 assert!(update_fail_malformed_htlcs.is_empty());
7057 assert!(update_fee.is_none());
7058 (update_fail_htlcs[0].clone(), commitment_signed)
7060 _ => panic!("Unexpected event"),
7062 check_added_monitors!(nodes[1], 1);
7064 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7065 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7067 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7068 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7069 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7070 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7074 fn test_announce_disable_channels() {
7075 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7076 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7078 let chanmon_cfgs = create_chanmon_cfgs(2);
7079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7081 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7083 create_announced_chan_between_nodes(&nodes, 0, 1);
7084 create_announced_chan_between_nodes(&nodes, 1, 0);
7085 create_announced_chan_between_nodes(&nodes, 0, 1);
7088 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7089 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7091 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7092 nodes[0].node.timer_tick_occurred();
7094 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7095 assert_eq!(msg_events.len(), 3);
7096 let mut chans_disabled = HashMap::new();
7097 for e in msg_events {
7099 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7100 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7101 // Check that each channel gets updated exactly once
7102 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7103 panic!("Generated ChannelUpdate for wrong chan!");
7106 _ => panic!("Unexpected event"),
7110 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();
7111 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7112 assert_eq!(reestablish_1.len(), 3);
7113 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();
7114 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7115 assert_eq!(reestablish_2.len(), 3);
7117 // Reestablish chan_1
7118 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7119 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7120 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7121 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7122 // Reestablish chan_2
7123 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7124 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7125 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7126 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7127 // Reestablish chan_3
7128 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7129 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7130 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7131 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7133 for _ in 0..ENABLE_GOSSIP_TICKS {
7134 nodes[0].node.timer_tick_occurred();
7136 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7137 nodes[0].node.timer_tick_occurred();
7138 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7139 assert_eq!(msg_events.len(), 3);
7140 for e in msg_events {
7142 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7143 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7144 match chans_disabled.remove(&msg.contents.short_channel_id) {
7145 // Each update should have a higher timestamp than the previous one, replacing
7147 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7148 None => panic!("Generated ChannelUpdate for wrong chan!"),
7151 _ => panic!("Unexpected event"),
7154 // Check that each channel gets updated exactly once
7155 assert!(chans_disabled.is_empty());
7159 fn test_bump_penalty_txn_on_revoked_commitment() {
7160 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7161 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7163 let chanmon_cfgs = create_chanmon_cfgs(2);
7164 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7165 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7166 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7168 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7170 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7171 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7172 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7173 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7174 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7176 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7177 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7178 assert_eq!(revoked_txn[0].output.len(), 4);
7179 assert_eq!(revoked_txn[0].input.len(), 1);
7180 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7181 let revoked_txid = revoked_txn[0].txid();
7183 let mut penalty_sum = 0;
7184 for outp in revoked_txn[0].output.iter() {
7185 if outp.script_pubkey.is_v0_p2wsh() {
7186 penalty_sum += outp.value;
7190 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7191 let header_114 = connect_blocks(&nodes[1], 14);
7193 // Actually revoke tx by claiming a HTLC
7194 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7195 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7196 check_added_monitors!(nodes[1], 1);
7198 // One or more justice tx should have been broadcast, check it
7202 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7203 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7204 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7205 assert_eq!(node_txn[0].output.len(), 1);
7206 check_spends!(node_txn[0], revoked_txn[0]);
7207 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7208 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7209 penalty_1 = node_txn[0].txid();
7213 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7214 connect_blocks(&nodes[1], 15);
7215 let mut penalty_2 = penalty_1;
7216 let mut feerate_2 = 0;
7218 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7219 assert_eq!(node_txn.len(), 1);
7220 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7221 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7222 assert_eq!(node_txn[0].output.len(), 1);
7223 check_spends!(node_txn[0], revoked_txn[0]);
7224 penalty_2 = node_txn[0].txid();
7225 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7226 assert_ne!(penalty_2, penalty_1);
7227 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7228 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7229 // Verify 25% bump heuristic
7230 assert!(feerate_2 * 100 >= feerate_1 * 125);
7234 assert_ne!(feerate_2, 0);
7236 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7237 connect_blocks(&nodes[1], 1);
7239 let mut feerate_3 = 0;
7241 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7242 assert_eq!(node_txn.len(), 1);
7243 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7244 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7245 assert_eq!(node_txn[0].output.len(), 1);
7246 check_spends!(node_txn[0], revoked_txn[0]);
7247 penalty_3 = node_txn[0].txid();
7248 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7249 assert_ne!(penalty_3, penalty_2);
7250 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7251 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7252 // Verify 25% bump heuristic
7253 assert!(feerate_3 * 100 >= feerate_2 * 125);
7257 assert_ne!(feerate_3, 0);
7259 nodes[1].node.get_and_clear_pending_events();
7260 nodes[1].node.get_and_clear_pending_msg_events();
7264 fn test_bump_penalty_txn_on_revoked_htlcs() {
7265 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7266 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7268 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7269 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7270 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7271 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7272 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7274 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7275 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7276 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7277 let scorer = test_utils::TestScorer::new();
7278 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7279 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7280 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7281 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7282 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7283 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7284 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7285 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7287 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7288 assert_eq!(revoked_local_txn[0].input.len(), 1);
7289 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7291 // Revoke local commitment tx
7292 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7294 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7295 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7296 check_closed_broadcast!(nodes[1], true);
7297 check_added_monitors!(nodes[1], 1);
7298 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7299 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7301 let revoked_htlc_txn = {
7302 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7303 assert_eq!(txn.len(), 2);
7305 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7306 assert_eq!(txn[0].input.len(), 1);
7307 check_spends!(txn[0], revoked_local_txn[0]);
7309 assert_eq!(txn[1].input.len(), 1);
7310 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7311 assert_eq!(txn[1].output.len(), 1);
7312 check_spends!(txn[1], revoked_local_txn[0]);
7317 // Broadcast set of revoked txn on A
7318 let hash_128 = connect_blocks(&nodes[0], 40);
7319 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7320 connect_block(&nodes[0], &block_11);
7321 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7322 connect_block(&nodes[0], &block_129);
7323 let events = nodes[0].node.get_and_clear_pending_events();
7324 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7325 match events.last().unwrap() {
7326 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7327 _ => panic!("Unexpected event"),
7333 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7334 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7335 // Verify claim tx are spending revoked HTLC txn
7337 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7338 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7339 // which are included in the same block (they are broadcasted because we scan the
7340 // transactions linearly and generate claims as we go, they likely should be removed in the
7342 assert_eq!(node_txn[0].input.len(), 1);
7343 check_spends!(node_txn[0], revoked_local_txn[0]);
7344 assert_eq!(node_txn[1].input.len(), 1);
7345 check_spends!(node_txn[1], revoked_local_txn[0]);
7346 assert_eq!(node_txn[2].input.len(), 1);
7347 check_spends!(node_txn[2], revoked_local_txn[0]);
7349 // Each of the three justice transactions claim a separate (single) output of the three
7350 // available, which we check here:
7351 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7352 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7353 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7355 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7356 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7358 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7359 // output, checked above).
7360 assert_eq!(node_txn[3].input.len(), 2);
7361 assert_eq!(node_txn[3].output.len(), 1);
7362 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7364 first = node_txn[3].txid();
7365 // Store both feerates for later comparison
7366 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7367 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7368 penalty_txn = vec![node_txn[2].clone()];
7372 // Connect one more block to see if bumped penalty are issued for HTLC txn
7373 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7374 connect_block(&nodes[0], &block_130);
7375 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7376 connect_block(&nodes[0], &block_131);
7378 // Few more blocks to confirm penalty txn
7379 connect_blocks(&nodes[0], 4);
7380 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7381 let header_144 = connect_blocks(&nodes[0], 9);
7383 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7384 assert_eq!(node_txn.len(), 1);
7386 assert_eq!(node_txn[0].input.len(), 2);
7387 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7388 // Verify bumped tx is different and 25% bump heuristic
7389 assert_ne!(first, node_txn[0].txid());
7390 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7391 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7392 assert!(feerate_2 * 100 > feerate_1 * 125);
7393 let txn = vec![node_txn[0].clone()];
7397 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7398 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7399 connect_blocks(&nodes[0], 20);
7401 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7402 // We verify than no new transaction has been broadcast because previously
7403 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7404 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7405 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7406 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7407 // up bumped justice generation.
7408 assert_eq!(node_txn.len(), 0);
7411 check_closed_broadcast!(nodes[0], true);
7412 check_added_monitors!(nodes[0], 1);
7416 fn test_bump_penalty_txn_on_remote_commitment() {
7417 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7418 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7421 // Provide preimage for one
7422 // Check aggregation
7424 let chanmon_cfgs = create_chanmon_cfgs(2);
7425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7427 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7429 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7430 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7431 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7433 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7434 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7435 assert_eq!(remote_txn[0].output.len(), 4);
7436 assert_eq!(remote_txn[0].input.len(), 1);
7437 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7439 // Claim a HTLC without revocation (provide B monitor with preimage)
7440 nodes[1].node.claim_funds(payment_preimage);
7441 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7442 mine_transaction(&nodes[1], &remote_txn[0]);
7443 check_added_monitors!(nodes[1], 2);
7444 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7446 // One or more claim tx should have been broadcast, check it
7450 let feerate_timeout;
7451 let feerate_preimage;
7453 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7454 // 3 transactions including:
7455 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7456 assert_eq!(node_txn.len(), 3);
7457 assert_eq!(node_txn[0].input.len(), 1);
7458 assert_eq!(node_txn[1].input.len(), 1);
7459 assert_eq!(node_txn[2].input.len(), 1);
7460 check_spends!(node_txn[0], remote_txn[0]);
7461 check_spends!(node_txn[1], remote_txn[0]);
7462 check_spends!(node_txn[2], remote_txn[0]);
7464 preimage = node_txn[0].txid();
7465 let index = node_txn[0].input[0].previous_output.vout;
7466 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7467 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7469 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7470 (node_txn[2].clone(), node_txn[1].clone())
7472 (node_txn[1].clone(), node_txn[2].clone())
7475 preimage_bump = preimage_bump_tx;
7476 check_spends!(preimage_bump, remote_txn[0]);
7477 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7479 timeout = timeout_tx.txid();
7480 let index = timeout_tx.input[0].previous_output.vout;
7481 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7482 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7486 assert_ne!(feerate_timeout, 0);
7487 assert_ne!(feerate_preimage, 0);
7489 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7490 connect_blocks(&nodes[1], 1);
7492 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7493 assert_eq!(node_txn.len(), 1);
7494 assert_eq!(node_txn[0].input.len(), 1);
7495 assert_eq!(preimage_bump.input.len(), 1);
7496 check_spends!(node_txn[0], remote_txn[0]);
7497 check_spends!(preimage_bump, remote_txn[0]);
7499 let index = preimage_bump.input[0].previous_output.vout;
7500 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7501 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7502 assert!(new_feerate * 100 > feerate_timeout * 125);
7503 assert_ne!(timeout, preimage_bump.txid());
7505 let index = node_txn[0].input[0].previous_output.vout;
7506 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7507 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7508 assert!(new_feerate * 100 > feerate_preimage * 125);
7509 assert_ne!(preimage, node_txn[0].txid());
7514 nodes[1].node.get_and_clear_pending_events();
7515 nodes[1].node.get_and_clear_pending_msg_events();
7519 fn test_counterparty_raa_skip_no_crash() {
7520 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7521 // commitment transaction, we would have happily carried on and provided them the next
7522 // commitment transaction based on one RAA forward. This would probably eventually have led to
7523 // channel closure, but it would not have resulted in funds loss. Still, our
7524 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7525 // check simply that the channel is closed in response to such an RAA, but don't check whether
7526 // we decide to punish our counterparty for revoking their funds (as we don't currently
7528 let chanmon_cfgs = create_chanmon_cfgs(2);
7529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7531 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7532 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7534 let per_commitment_secret;
7535 let next_per_commitment_point;
7537 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7538 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7539 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7541 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7543 // Make signer believe we got a counterparty signature, so that it allows the revocation
7544 keys.get_enforcement_state().last_holder_commitment -= 1;
7545 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7547 // Must revoke without gaps
7548 keys.get_enforcement_state().last_holder_commitment -= 1;
7549 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7551 keys.get_enforcement_state().last_holder_commitment -= 1;
7552 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7553 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7556 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7557 &msgs::RevokeAndACK {
7559 per_commitment_secret,
7560 next_per_commitment_point,
7562 next_local_nonce: None,
7564 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7565 check_added_monitors!(nodes[1], 1);
7566 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7570 fn test_bump_txn_sanitize_tracking_maps() {
7571 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7572 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7574 let chanmon_cfgs = create_chanmon_cfgs(2);
7575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7579 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7580 // Lock HTLC in both directions
7581 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7582 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7584 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7585 assert_eq!(revoked_local_txn[0].input.len(), 1);
7586 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7588 // Revoke local commitment tx
7589 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7591 // Broadcast set of revoked txn on A
7592 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7593 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7594 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7596 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7597 check_closed_broadcast!(nodes[0], true);
7598 check_added_monitors!(nodes[0], 1);
7599 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7601 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7602 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7603 check_spends!(node_txn[0], revoked_local_txn[0]);
7604 check_spends!(node_txn[1], revoked_local_txn[0]);
7605 check_spends!(node_txn[2], revoked_local_txn[0]);
7606 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7610 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7611 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7613 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7614 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7615 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7620 fn test_channel_conf_timeout() {
7621 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7622 // confirm within 2016 blocks, as recommended by BOLT 2.
7623 let chanmon_cfgs = create_chanmon_cfgs(2);
7624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7626 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7628 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7630 // The outbound node should wait forever for confirmation:
7631 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7632 // copied here instead of directly referencing the constant.
7633 connect_blocks(&nodes[0], 2016);
7634 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7636 // The inbound node should fail the channel after exactly 2016 blocks
7637 connect_blocks(&nodes[1], 2015);
7638 check_added_monitors!(nodes[1], 0);
7639 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7641 connect_blocks(&nodes[1], 1);
7642 check_added_monitors!(nodes[1], 1);
7643 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7644 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7645 assert_eq!(close_ev.len(), 1);
7647 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7648 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7649 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7651 _ => panic!("Unexpected event"),
7656 fn test_override_channel_config() {
7657 let chanmon_cfgs = create_chanmon_cfgs(2);
7658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7660 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7662 // Node0 initiates a channel to node1 using the override config.
7663 let mut override_config = UserConfig::default();
7664 override_config.channel_handshake_config.our_to_self_delay = 200;
7666 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7668 // Assert the channel created by node0 is using the override config.
7669 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7670 assert_eq!(res.channel_flags, 0);
7671 assert_eq!(res.to_self_delay, 200);
7675 fn test_override_0msat_htlc_minimum() {
7676 let mut zero_config = UserConfig::default();
7677 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7678 let chanmon_cfgs = create_chanmon_cfgs(2);
7679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7681 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7683 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7684 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7685 assert_eq!(res.htlc_minimum_msat, 1);
7687 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7688 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7689 assert_eq!(res.htlc_minimum_msat, 1);
7693 fn test_channel_update_has_correct_htlc_maximum_msat() {
7694 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7695 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7696 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7697 // 90% of the `channel_value`.
7698 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7700 let mut config_30_percent = UserConfig::default();
7701 config_30_percent.channel_handshake_config.announced_channel = true;
7702 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7703 let mut config_50_percent = UserConfig::default();
7704 config_50_percent.channel_handshake_config.announced_channel = true;
7705 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7706 let mut config_95_percent = UserConfig::default();
7707 config_95_percent.channel_handshake_config.announced_channel = true;
7708 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7709 let mut config_100_percent = UserConfig::default();
7710 config_100_percent.channel_handshake_config.announced_channel = true;
7711 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7713 let chanmon_cfgs = create_chanmon_cfgs(4);
7714 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7715 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)]);
7716 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7718 let channel_value_satoshis = 100000;
7719 let channel_value_msat = channel_value_satoshis * 1000;
7720 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7721 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7722 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7724 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7725 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7727 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7728 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7729 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7730 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7731 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7732 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7734 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7735 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7737 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7738 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7739 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7741 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7745 fn test_manually_accept_inbound_channel_request() {
7746 let mut manually_accept_conf = UserConfig::default();
7747 manually_accept_conf.manually_accept_inbound_channels = true;
7748 let chanmon_cfgs = create_chanmon_cfgs(2);
7749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7751 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7753 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7754 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7756 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7758 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7759 // accepting the inbound channel request.
7760 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7762 let events = nodes[1].node.get_and_clear_pending_events();
7764 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7765 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7767 _ => panic!("Unexpected event"),
7770 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7771 assert_eq!(accept_msg_ev.len(), 1);
7773 match accept_msg_ev[0] {
7774 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7775 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7777 _ => panic!("Unexpected event"),
7780 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7782 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7783 assert_eq!(close_msg_ev.len(), 1);
7785 let events = nodes[1].node.get_and_clear_pending_events();
7787 Event::ChannelClosed { user_channel_id, .. } => {
7788 assert_eq!(user_channel_id, 23);
7790 _ => panic!("Unexpected event"),
7795 fn test_manually_reject_inbound_channel_request() {
7796 let mut manually_accept_conf = UserConfig::default();
7797 manually_accept_conf.manually_accept_inbound_channels = true;
7798 let chanmon_cfgs = create_chanmon_cfgs(2);
7799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7801 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7803 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7804 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7806 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7808 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7809 // rejecting the inbound channel request.
7810 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7812 let events = nodes[1].node.get_and_clear_pending_events();
7814 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7815 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7817 _ => panic!("Unexpected event"),
7820 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7821 assert_eq!(close_msg_ev.len(), 1);
7823 match close_msg_ev[0] {
7824 MessageSendEvent::HandleError { ref node_id, .. } => {
7825 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7827 _ => panic!("Unexpected event"),
7829 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7833 fn test_reject_funding_before_inbound_channel_accepted() {
7834 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7835 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7836 // the node operator before the counterparty sends a `FundingCreated` message. If a
7837 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7838 // and the channel should be closed.
7839 let mut manually_accept_conf = UserConfig::default();
7840 manually_accept_conf.manually_accept_inbound_channels = true;
7841 let chanmon_cfgs = create_chanmon_cfgs(2);
7842 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7843 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7844 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7846 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7847 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7848 let temp_channel_id = res.temporary_channel_id;
7850 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7852 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7853 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7855 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7856 nodes[1].node.get_and_clear_pending_events();
7858 // Get the `AcceptChannel` message of `nodes[1]` without calling
7859 // `ChannelManager::accept_inbound_channel`, which generates a
7860 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7861 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7862 // succeed when `nodes[0]` is passed to it.
7863 let accept_chan_msg = {
7864 let mut node_1_per_peer_lock;
7865 let mut node_1_peer_state_lock;
7866 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7867 channel.get_accept_channel_message()
7869 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7871 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7873 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7874 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7876 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7877 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7879 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7880 assert_eq!(close_msg_ev.len(), 1);
7882 let expected_err = "FundingCreated message received before the channel was accepted";
7883 match close_msg_ev[0] {
7884 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7885 assert_eq!(msg.channel_id, temp_channel_id);
7886 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7887 assert_eq!(msg.data, expected_err);
7889 _ => panic!("Unexpected event"),
7892 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7896 fn test_can_not_accept_inbound_channel_twice() {
7897 let mut manually_accept_conf = UserConfig::default();
7898 manually_accept_conf.manually_accept_inbound_channels = true;
7899 let chanmon_cfgs = create_chanmon_cfgs(2);
7900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7904 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7905 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7907 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7909 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7910 // accepting the inbound channel request.
7911 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7913 let events = nodes[1].node.get_and_clear_pending_events();
7915 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7916 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7917 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7919 Err(APIError::APIMisuseError { err }) => {
7920 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7922 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7923 Err(_) => panic!("Unexpected Error"),
7926 _ => panic!("Unexpected event"),
7929 // Ensure that the channel wasn't closed after attempting to accept it twice.
7930 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7931 assert_eq!(accept_msg_ev.len(), 1);
7933 match accept_msg_ev[0] {
7934 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7935 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7937 _ => panic!("Unexpected event"),
7942 fn test_can_not_accept_unknown_inbound_channel() {
7943 let chanmon_cfg = create_chanmon_cfgs(2);
7944 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7945 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7946 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7948 let unknown_channel_id = [0; 32];
7949 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7951 Err(APIError::ChannelUnavailable { err }) => {
7952 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()));
7954 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7955 Err(_) => panic!("Unexpected Error"),
7960 fn test_onion_value_mpp_set_calculation() {
7961 // Test that we use the onion value `amt_to_forward` when
7962 // calculating whether we've reached the `total_msat` of an MPP
7963 // by having a routing node forward more than `amt_to_forward`
7964 // and checking that the receiving node doesn't generate
7965 // a PaymentClaimable event too early
7967 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7968 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7969 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7970 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7972 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7973 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7974 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7975 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7977 let total_msat = 100_000;
7978 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7979 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7980 let sample_path = route.paths.pop().unwrap();
7982 let mut path_1 = sample_path.clone();
7983 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7984 path_1.hops[0].short_channel_id = chan_1_id;
7985 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7986 path_1.hops[1].short_channel_id = chan_3_id;
7987 path_1.hops[1].fee_msat = 100_000;
7988 route.paths.push(path_1);
7990 let mut path_2 = sample_path.clone();
7991 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
7992 path_2.hops[0].short_channel_id = chan_2_id;
7993 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
7994 path_2.hops[1].short_channel_id = chan_4_id;
7995 path_2.hops[1].fee_msat = 1_000;
7996 route.paths.push(path_2);
7999 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8000 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8001 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8002 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8003 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8004 check_added_monitors!(nodes[0], expected_paths.len());
8006 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8007 assert_eq!(events.len(), expected_paths.len());
8010 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8011 let mut payment_event = SendEvent::from_event(ev);
8012 let mut prev_node = &nodes[0];
8014 for (idx, &node) in expected_paths[0].iter().enumerate() {
8015 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8017 if idx == 0 { // routing node
8018 let session_priv = [3; 32];
8019 let height = nodes[0].best_block_info().1;
8020 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8021 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8022 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8023 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8024 // Edit amt_to_forward to simulate the sender having set
8025 // the final amount and the routing node taking less fee
8026 onion_payloads[1].amt_to_forward = 99_000;
8027 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8028 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8031 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8032 check_added_monitors!(node, 0);
8033 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8034 expect_pending_htlcs_forwardable!(node);
8037 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8038 assert_eq!(events_2.len(), 1);
8039 check_added_monitors!(node, 1);
8040 payment_event = SendEvent::from_event(events_2.remove(0));
8041 assert_eq!(payment_event.msgs.len(), 1);
8043 let events_2 = node.node.get_and_clear_pending_events();
8044 assert!(events_2.is_empty());
8051 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8052 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8054 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8057 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8059 let routing_node_count = msat_amounts.len();
8060 let node_count = routing_node_count + 2;
8062 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8063 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8064 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8065 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8070 // Create channels for each amount
8071 let mut expected_paths = Vec::with_capacity(routing_node_count);
8072 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8073 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8074 for i in 0..routing_node_count {
8075 let routing_node = 2 + i;
8076 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8077 src_chan_ids.push(src_chan_id);
8078 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8079 dst_chan_ids.push(dst_chan_id);
8080 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8081 expected_paths.push(path);
8083 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8085 // Create a route for each amount
8086 let example_amount = 100000;
8087 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);
8088 let sample_path = route.paths.pop().unwrap();
8089 for i in 0..routing_node_count {
8090 let routing_node = 2 + i;
8091 let mut path = sample_path.clone();
8092 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8093 path.hops[0].short_channel_id = src_chan_ids[i];
8094 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8095 path.hops[1].short_channel_id = dst_chan_ids[i];
8096 path.hops[1].fee_msat = msat_amounts[i];
8097 route.paths.push(path);
8100 // Send payment with manually set total_msat
8101 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8102 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8103 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8104 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8105 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8106 check_added_monitors!(nodes[src_idx], expected_paths.len());
8108 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8109 assert_eq!(events.len(), expected_paths.len());
8110 let mut amount_received = 0;
8111 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8112 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8114 let current_path_amount = msat_amounts[path_idx];
8115 amount_received += current_path_amount;
8116 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8117 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8120 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8124 fn test_overshoot_mpp() {
8125 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8126 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8130 fn test_simple_mpp() {
8131 // Simple test of sending a multi-path payment.
8132 let chanmon_cfgs = create_chanmon_cfgs(4);
8133 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8134 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8135 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8137 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8138 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8139 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8140 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8142 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8143 let path = route.paths[0].clone();
8144 route.paths.push(path);
8145 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8146 route.paths[0].hops[0].short_channel_id = chan_1_id;
8147 route.paths[0].hops[1].short_channel_id = chan_3_id;
8148 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8149 route.paths[1].hops[0].short_channel_id = chan_2_id;
8150 route.paths[1].hops[1].short_channel_id = chan_4_id;
8151 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8152 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8156 fn test_preimage_storage() {
8157 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8158 let chanmon_cfgs = create_chanmon_cfgs(2);
8159 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8160 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8161 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8163 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8166 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8167 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8168 nodes[0].node.send_payment_with_route(&route, payment_hash,
8169 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8170 check_added_monitors!(nodes[0], 1);
8171 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8172 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8173 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8174 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8176 // Note that after leaving the above scope we have no knowledge of any arguments or return
8177 // values from previous calls.
8178 expect_pending_htlcs_forwardable!(nodes[1]);
8179 let events = nodes[1].node.get_and_clear_pending_events();
8180 assert_eq!(events.len(), 1);
8182 Event::PaymentClaimable { ref purpose, .. } => {
8184 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8185 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8187 _ => panic!("expected PaymentPurpose::InvoicePayment")
8190 _ => panic!("Unexpected event"),
8195 #[allow(deprecated)]
8196 fn test_secret_timeout() {
8197 // Simple test of payment secret storage time outs. After
8198 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8199 let chanmon_cfgs = create_chanmon_cfgs(2);
8200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8202 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8204 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8206 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8208 // We should fail to register the same payment hash twice, at least until we've connected a
8209 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8210 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8211 assert_eq!(err, "Duplicate payment hash");
8212 } else { panic!(); }
8214 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8215 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8217 connect_block(&nodes[1], &block);
8218 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8219 assert_eq!(err, "Duplicate payment hash");
8220 } else { panic!(); }
8222 // If we then connect the second block, we should be able to register the same payment hash
8223 // again (this time getting a new payment secret).
8224 block.header.prev_blockhash = block.header.block_hash();
8225 block.header.time += 1;
8226 connect_block(&nodes[1], &block);
8227 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8228 assert_ne!(payment_secret_1, our_payment_secret);
8231 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8232 nodes[0].node.send_payment_with_route(&route, payment_hash,
8233 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8234 check_added_monitors!(nodes[0], 1);
8235 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8236 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8237 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8238 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8240 // Note that after leaving the above scope we have no knowledge of any arguments or return
8241 // values from previous calls.
8242 expect_pending_htlcs_forwardable!(nodes[1]);
8243 let events = nodes[1].node.get_and_clear_pending_events();
8244 assert_eq!(events.len(), 1);
8246 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8247 assert!(payment_preimage.is_none());
8248 assert_eq!(payment_secret, our_payment_secret);
8249 // We don't actually have the payment preimage with which to claim this payment!
8251 _ => panic!("Unexpected event"),
8256 fn test_bad_secret_hash() {
8257 // Simple test of unregistered payment hash/invalid payment secret handling
8258 let chanmon_cfgs = create_chanmon_cfgs(2);
8259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8261 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8263 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8265 let random_payment_hash = PaymentHash([42; 32]);
8266 let random_payment_secret = PaymentSecret([43; 32]);
8267 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8268 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8270 // All the below cases should end up being handled exactly identically, so we macro the
8271 // resulting events.
8272 macro_rules! handle_unknown_invalid_payment_data {
8273 ($payment_hash: expr) => {
8274 check_added_monitors!(nodes[0], 1);
8275 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8276 let payment_event = SendEvent::from_event(events.pop().unwrap());
8277 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8278 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8280 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8281 // again to process the pending backwards-failure of the HTLC
8282 expect_pending_htlcs_forwardable!(nodes[1]);
8283 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8284 check_added_monitors!(nodes[1], 1);
8286 // We should fail the payment back
8287 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8288 match events.pop().unwrap() {
8289 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8290 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8291 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8293 _ => panic!("Unexpected event"),
8298 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8299 // Error data is the HTLC value (100,000) and current block height
8300 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8302 // Send a payment with the right payment hash but the wrong payment secret
8303 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8304 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8305 handle_unknown_invalid_payment_data!(our_payment_hash);
8306 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8308 // Send a payment with a random payment hash, but the right payment secret
8309 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8310 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8311 handle_unknown_invalid_payment_data!(random_payment_hash);
8312 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8314 // Send a payment with a random payment hash and random payment secret
8315 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8316 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8317 handle_unknown_invalid_payment_data!(random_payment_hash);
8318 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8322 fn test_update_err_monitor_lockdown() {
8323 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8324 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8325 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8328 // This scenario may happen in a watchtower setup, where watchtower process a block height
8329 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8330 // commitment at same time.
8332 let chanmon_cfgs = create_chanmon_cfgs(2);
8333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8335 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8337 // Create some initial channel
8338 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8339 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8341 // Rebalance the network to generate htlc in the two directions
8342 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8344 // Route a HTLC from node 0 to node 1 (but don't settle)
8345 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8347 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8348 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8349 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8350 let persister = test_utils::TestPersister::new();
8353 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8354 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8355 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8356 assert!(new_monitor == *monitor);
8359 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);
8360 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8363 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8364 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8365 // transaction lock time requirements here.
8366 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8367 watchtower.chain_monitor.block_connected(&block, 200);
8369 // Try to update ChannelMonitor
8370 nodes[1].node.claim_funds(preimage);
8371 check_added_monitors!(nodes[1], 1);
8372 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8374 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8375 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8376 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8378 let mut node_0_per_peer_lock;
8379 let mut node_0_peer_state_lock;
8380 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8381 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8382 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8383 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8384 } else { assert!(false); }
8386 // Our local monitor is in-sync and hasn't processed yet timeout
8387 check_added_monitors!(nodes[0], 1);
8388 let events = nodes[0].node.get_and_clear_pending_events();
8389 assert_eq!(events.len(), 1);
8393 fn test_concurrent_monitor_claim() {
8394 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8395 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8396 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8397 // state N+1 confirms. Alice claims output from state N+1.
8399 let chanmon_cfgs = create_chanmon_cfgs(2);
8400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8402 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8404 // Create some initial channel
8405 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8406 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8408 // Rebalance the network to generate htlc in the two directions
8409 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8411 // Route a HTLC from node 0 to node 1 (but don't settle)
8412 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8414 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8415 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8416 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8417 let persister = test_utils::TestPersister::new();
8418 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8419 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8421 let watchtower_alice = {
8423 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8424 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8425 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8426 assert!(new_monitor == *monitor);
8429 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8430 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8433 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8434 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8435 // requirements here.
8436 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8437 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8438 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8440 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8442 let mut txn = alice_broadcaster.txn_broadcast();
8443 assert_eq!(txn.len(), 2);
8447 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8448 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8449 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8450 let persister = test_utils::TestPersister::new();
8451 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8452 let watchtower_bob = {
8454 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8455 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8456 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8457 assert!(new_monitor == *monitor);
8460 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8461 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8464 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8466 // Route another payment to generate another update with still previous HTLC pending
8467 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8468 nodes[1].node.send_payment_with_route(&route, payment_hash,
8469 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8470 check_added_monitors!(nodes[1], 1);
8472 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8473 assert_eq!(updates.update_add_htlcs.len(), 1);
8474 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8476 let mut node_0_per_peer_lock;
8477 let mut node_0_peer_state_lock;
8478 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8479 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8480 // Watchtower Alice should already have seen the block and reject the update
8481 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8482 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8483 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8484 } else { assert!(false); }
8486 // Our local monitor is in-sync and hasn't processed yet timeout
8487 check_added_monitors!(nodes[0], 1);
8489 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8490 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8492 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8495 let mut txn = bob_broadcaster.txn_broadcast();
8496 assert_eq!(txn.len(), 2);
8497 bob_state_y = txn.remove(0);
8500 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8501 let height = HTLC_TIMEOUT_BROADCAST + 1;
8502 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8503 check_closed_broadcast(&nodes[0], 1, true);
8504 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8505 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8506 check_added_monitors(&nodes[0], 1);
8508 let htlc_txn = alice_broadcaster.txn_broadcast();
8509 assert_eq!(htlc_txn.len(), 2);
8510 check_spends!(htlc_txn[0], bob_state_y);
8511 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8512 // it. However, she should, because it now has an invalid parent.
8513 check_spends!(htlc_txn[1], alice_state);
8518 fn test_pre_lockin_no_chan_closed_update() {
8519 // Test that if a peer closes a channel in response to a funding_created message we don't
8520 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8523 // Doing so would imply a channel monitor update before the initial channel monitor
8524 // registration, violating our API guarantees.
8526 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8527 // then opening a second channel with the same funding output as the first (which is not
8528 // rejected because the first channel does not exist in the ChannelManager) and closing it
8529 // before receiving funding_signed.
8530 let chanmon_cfgs = create_chanmon_cfgs(2);
8531 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8532 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8533 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8535 // Create an initial channel
8536 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8537 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8538 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8539 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8540 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8542 // Move the first channel through the funding flow...
8543 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8545 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8546 check_added_monitors!(nodes[0], 0);
8548 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8549 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8550 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8551 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8552 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8556 fn test_htlc_no_detection() {
8557 // This test is a mutation to underscore the detection logic bug we had
8558 // before #653. HTLC value routed is above the remaining balance, thus
8559 // inverting HTLC and `to_remote` output. HTLC will come second and
8560 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8561 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8562 // outputs order detection for correct spending children filtring.
8564 let chanmon_cfgs = create_chanmon_cfgs(2);
8565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8567 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8569 // Create some initial channels
8570 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8572 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8573 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8574 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8575 assert_eq!(local_txn[0].input.len(), 1);
8576 assert_eq!(local_txn[0].output.len(), 3);
8577 check_spends!(local_txn[0], chan_1.3);
8579 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8580 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8581 connect_block(&nodes[0], &block);
8582 // We deliberately connect the local tx twice as this should provoke a failure calling
8583 // this test before #653 fix.
8584 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8585 check_closed_broadcast!(nodes[0], true);
8586 check_added_monitors!(nodes[0], 1);
8587 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8588 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8590 let htlc_timeout = {
8591 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8592 assert_eq!(node_txn.len(), 1);
8593 assert_eq!(node_txn[0].input.len(), 1);
8594 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8595 check_spends!(node_txn[0], local_txn[0]);
8599 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8600 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8601 expect_payment_failed!(nodes[0], our_payment_hash, false);
8604 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8605 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8606 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8607 // Carol, Alice would be the upstream node, and Carol the downstream.)
8609 // Steps of the test:
8610 // 1) Alice sends a HTLC to Carol through Bob.
8611 // 2) Carol doesn't settle the HTLC.
8612 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8613 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8614 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8615 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8616 // 5) Carol release the preimage to Bob off-chain.
8617 // 6) Bob claims the offered output on the broadcasted commitment.
8618 let chanmon_cfgs = create_chanmon_cfgs(3);
8619 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8620 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8621 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8623 // Create some initial channels
8624 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8625 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8627 // Steps (1) and (2):
8628 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8629 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8631 // Check that Alice's commitment transaction now contains an output for this HTLC.
8632 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8633 check_spends!(alice_txn[0], chan_ab.3);
8634 assert_eq!(alice_txn[0].output.len(), 2);
8635 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8636 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8637 assert_eq!(alice_txn.len(), 2);
8639 // Steps (3) and (4):
8640 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8641 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8642 let mut force_closing_node = 0; // Alice force-closes
8643 let mut counterparty_node = 1; // Bob if Alice force-closes
8646 if !broadcast_alice {
8647 force_closing_node = 1;
8648 counterparty_node = 0;
8650 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8651 check_closed_broadcast!(nodes[force_closing_node], true);
8652 check_added_monitors!(nodes[force_closing_node], 1);
8653 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8654 if go_onchain_before_fulfill {
8655 let txn_to_broadcast = match broadcast_alice {
8656 true => alice_txn.clone(),
8657 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8659 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8660 if broadcast_alice {
8661 check_closed_broadcast!(nodes[1], true);
8662 check_added_monitors!(nodes[1], 1);
8663 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8668 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8669 // process of removing the HTLC from their commitment transactions.
8670 nodes[2].node.claim_funds(payment_preimage);
8671 check_added_monitors!(nodes[2], 1);
8672 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8674 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8675 assert!(carol_updates.update_add_htlcs.is_empty());
8676 assert!(carol_updates.update_fail_htlcs.is_empty());
8677 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8678 assert!(carol_updates.update_fee.is_none());
8679 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8681 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8682 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8683 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8684 if !go_onchain_before_fulfill && broadcast_alice {
8685 let events = nodes[1].node.get_and_clear_pending_msg_events();
8686 assert_eq!(events.len(), 1);
8688 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8689 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8691 _ => panic!("Unexpected event"),
8694 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8695 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8696 // Carol<->Bob's updated commitment transaction info.
8697 check_added_monitors!(nodes[1], 2);
8699 let events = nodes[1].node.get_and_clear_pending_msg_events();
8700 assert_eq!(events.len(), 2);
8701 let bob_revocation = match events[0] {
8702 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8703 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8706 _ => panic!("Unexpected event"),
8708 let bob_updates = match events[1] {
8709 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8710 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8713 _ => panic!("Unexpected event"),
8716 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8717 check_added_monitors!(nodes[2], 1);
8718 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8719 check_added_monitors!(nodes[2], 1);
8721 let events = nodes[2].node.get_and_clear_pending_msg_events();
8722 assert_eq!(events.len(), 1);
8723 let carol_revocation = match events[0] {
8724 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8725 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8728 _ => panic!("Unexpected event"),
8730 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8731 check_added_monitors!(nodes[1], 1);
8733 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8734 // here's where we put said channel's commitment tx on-chain.
8735 let mut txn_to_broadcast = alice_txn.clone();
8736 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8737 if !go_onchain_before_fulfill {
8738 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8739 // If Bob was the one to force-close, he will have already passed these checks earlier.
8740 if broadcast_alice {
8741 check_closed_broadcast!(nodes[1], true);
8742 check_added_monitors!(nodes[1], 1);
8743 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8745 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8746 if broadcast_alice {
8747 assert_eq!(bob_txn.len(), 1);
8748 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8750 assert_eq!(bob_txn.len(), 2);
8751 check_spends!(bob_txn[0], chan_ab.3);
8756 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8757 // broadcasted commitment transaction.
8759 let script_weight = match broadcast_alice {
8760 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8761 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8763 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8764 // Bob force-closed and broadcasts the commitment transaction along with a
8765 // HTLC-output-claiming transaction.
8766 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8767 if broadcast_alice {
8768 assert_eq!(bob_txn.len(), 1);
8769 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8770 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8772 assert_eq!(bob_txn.len(), 2);
8773 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8774 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8780 fn test_onchain_htlc_settlement_after_close() {
8781 do_test_onchain_htlc_settlement_after_close(true, true);
8782 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8783 do_test_onchain_htlc_settlement_after_close(true, false);
8784 do_test_onchain_htlc_settlement_after_close(false, false);
8788 fn test_duplicate_temporary_channel_id_from_different_peers() {
8789 // Tests that we can accept two different `OpenChannel` requests with the same
8790 // `temporary_channel_id`, as long as they are from different peers.
8791 let chanmon_cfgs = create_chanmon_cfgs(3);
8792 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8793 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8794 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8796 // Create an first channel channel
8797 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8798 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8800 // Create an second channel
8801 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8802 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8804 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8805 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8806 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8808 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8809 // `temporary_channel_id` as they are from different peers.
8810 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8812 let events = nodes[0].node.get_and_clear_pending_msg_events();
8813 assert_eq!(events.len(), 1);
8815 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8816 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8817 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8819 _ => panic!("Unexpected event"),
8823 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8825 let events = nodes[0].node.get_and_clear_pending_msg_events();
8826 assert_eq!(events.len(), 1);
8828 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8829 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8830 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8832 _ => panic!("Unexpected event"),
8838 fn test_duplicate_chan_id() {
8839 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8840 // already open we reject it and keep the old channel.
8842 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8843 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8844 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8845 // updating logic for the existing channel.
8846 let chanmon_cfgs = create_chanmon_cfgs(2);
8847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8851 // Create an initial channel
8852 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8853 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8854 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8855 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()));
8857 // Try to create a second channel with the same temporary_channel_id as the first and check
8858 // that it is rejected.
8859 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8861 let events = nodes[1].node.get_and_clear_pending_msg_events();
8862 assert_eq!(events.len(), 1);
8864 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8865 // Technically, at this point, nodes[1] would be justified in thinking both the
8866 // first (valid) and second (invalid) channels are closed, given they both have
8867 // the same non-temporary channel_id. However, currently we do not, so we just
8868 // move forward with it.
8869 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8870 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8872 _ => panic!("Unexpected event"),
8876 // Move the first channel through the funding flow...
8877 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8879 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8880 check_added_monitors!(nodes[0], 0);
8882 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8883 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8885 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8886 assert_eq!(added_monitors.len(), 1);
8887 assert_eq!(added_monitors[0].0, funding_output);
8888 added_monitors.clear();
8890 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8892 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8894 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8895 let channel_id = funding_outpoint.to_channel_id();
8897 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8900 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8901 // Technically this is allowed by the spec, but we don't support it and there's little reason
8902 // to. Still, it shouldn't cause any other issues.
8903 open_chan_msg.temporary_channel_id = channel_id;
8904 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8906 let events = nodes[1].node.get_and_clear_pending_msg_events();
8907 assert_eq!(events.len(), 1);
8909 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8910 // Technically, at this point, nodes[1] would be justified in thinking both
8911 // channels are closed, but currently we do not, so we just move forward with it.
8912 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8913 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8915 _ => panic!("Unexpected event"),
8919 // Now try to create a second channel which has a duplicate funding output.
8920 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8921 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8922 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8923 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()));
8924 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8926 let funding_created = {
8927 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8928 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8929 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8930 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8931 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8932 // channelmanager in a possibly nonsense state instead).
8933 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8934 let logger = test_utils::TestLogger::new();
8935 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8937 check_added_monitors!(nodes[0], 0);
8938 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8939 // At this point we'll look up if the channel_id is present and immediately fail the channel
8940 // without trying to persist the `ChannelMonitor`.
8941 check_added_monitors!(nodes[1], 0);
8943 // ...still, nodes[1] will reject the duplicate channel.
8945 let events = nodes[1].node.get_and_clear_pending_msg_events();
8946 assert_eq!(events.len(), 1);
8948 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8949 // Technically, at this point, nodes[1] would be justified in thinking both
8950 // channels are closed, but currently we do not, so we just move forward with it.
8951 assert_eq!(msg.channel_id, channel_id);
8952 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8954 _ => panic!("Unexpected event"),
8958 // finally, finish creating the original channel and send a payment over it to make sure
8959 // everything is functional.
8960 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8962 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8963 assert_eq!(added_monitors.len(), 1);
8964 assert_eq!(added_monitors[0].0, funding_output);
8965 added_monitors.clear();
8967 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8969 let events_4 = nodes[0].node.get_and_clear_pending_events();
8970 assert_eq!(events_4.len(), 0);
8971 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8972 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8974 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8975 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8976 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8978 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8982 fn test_error_chans_closed() {
8983 // Test that we properly handle error messages, closing appropriate channels.
8985 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8986 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8987 // we can test various edge cases around it to ensure we don't regress.
8988 let chanmon_cfgs = create_chanmon_cfgs(3);
8989 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8990 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8991 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8993 // Create some initial channels
8994 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8995 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8996 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8998 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8999 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9000 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9002 // Closing a channel from a different peer has no effect
9003 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9004 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9006 // Closing one channel doesn't impact others
9007 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9008 check_added_monitors!(nodes[0], 1);
9009 check_closed_broadcast!(nodes[0], false);
9010 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9011 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9012 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9013 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);
9014 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);
9016 // A null channel ID should close all channels
9017 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9018 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9019 check_added_monitors!(nodes[0], 2);
9020 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9021 let events = nodes[0].node.get_and_clear_pending_msg_events();
9022 assert_eq!(events.len(), 2);
9024 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9025 assert_eq!(msg.contents.flags & 2, 2);
9027 _ => panic!("Unexpected event"),
9030 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9031 assert_eq!(msg.contents.flags & 2, 2);
9033 _ => panic!("Unexpected event"),
9035 // Note that at this point users of a standard PeerHandler will end up calling
9036 // peer_disconnected.
9037 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9038 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9040 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9041 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9042 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9046 fn test_invalid_funding_tx() {
9047 // Test that we properly handle invalid funding transactions sent to us from a peer.
9049 // Previously, all other major lightning implementations had failed to properly sanitize
9050 // funding transactions from their counterparties, leading to a multi-implementation critical
9051 // security vulnerability (though we always sanitized properly, we've previously had
9052 // un-released crashes in the sanitization process).
9054 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9055 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9056 // gave up on it. We test this here by generating such a transaction.
9057 let chanmon_cfgs = create_chanmon_cfgs(2);
9058 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9059 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9060 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9062 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9063 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()));
9064 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()));
9066 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9068 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9069 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9070 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9072 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9073 let wit_program_script: Script = wit_program.into();
9074 for output in tx.output.iter_mut() {
9075 // Make the confirmed funding transaction have a bogus script_pubkey
9076 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9079 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9080 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()));
9081 check_added_monitors!(nodes[1], 1);
9082 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9084 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()));
9085 check_added_monitors!(nodes[0], 1);
9086 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9088 let events_1 = nodes[0].node.get_and_clear_pending_events();
9089 assert_eq!(events_1.len(), 0);
9091 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9092 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9093 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9095 let expected_err = "funding tx had wrong script/value or output index";
9096 confirm_transaction_at(&nodes[1], &tx, 1);
9097 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9098 check_added_monitors!(nodes[1], 1);
9099 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9100 assert_eq!(events_2.len(), 1);
9101 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9102 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9103 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9104 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9105 } else { panic!(); }
9106 } else { panic!(); }
9107 assert_eq!(nodes[1].node.list_channels().len(), 0);
9109 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9110 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9111 // as its not 32 bytes long.
9112 let mut spend_tx = Transaction {
9113 version: 2i32, lock_time: PackedLockTime::ZERO,
9114 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9115 previous_output: BitcoinOutPoint {
9119 script_sig: Script::new(),
9120 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9121 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9123 output: vec![TxOut {
9125 script_pubkey: Script::new(),
9128 check_spends!(spend_tx, tx);
9129 mine_transaction(&nodes[1], &spend_tx);
9132 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9133 // In the first version of the chain::Confirm interface, after a refactor was made to not
9134 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9135 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9136 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9137 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9138 // spending transaction until height N+1 (or greater). This was due to the way
9139 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9140 // spending transaction at the height the input transaction was confirmed at, not whether we
9141 // should broadcast a spending transaction at the current height.
9142 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9143 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9144 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9145 // until we learned about an additional block.
9147 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9148 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9149 let chanmon_cfgs = create_chanmon_cfgs(3);
9150 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9151 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9152 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9153 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9155 create_announced_chan_between_nodes(&nodes, 0, 1);
9156 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9157 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9158 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9159 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9161 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9162 check_closed_broadcast!(nodes[1], true);
9163 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9164 check_added_monitors!(nodes[1], 1);
9165 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9166 assert_eq!(node_txn.len(), 1);
9168 let conf_height = nodes[1].best_block_info().1;
9169 if !test_height_before_timelock {
9170 connect_blocks(&nodes[1], 24 * 6);
9172 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9173 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9174 if test_height_before_timelock {
9175 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9176 // generate any events or broadcast any transactions
9177 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9178 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9180 // We should broadcast an HTLC transaction spending our funding transaction first
9181 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9182 assert_eq!(spending_txn.len(), 2);
9183 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9184 check_spends!(spending_txn[1], node_txn[0]);
9185 // We should also generate a SpendableOutputs event with the to_self output (as its
9187 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9188 assert_eq!(descriptor_spend_txn.len(), 1);
9190 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9191 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9192 // additional block built on top of the current chain.
9193 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9194 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9195 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 }]);
9196 check_added_monitors!(nodes[1], 1);
9198 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9199 assert!(updates.update_add_htlcs.is_empty());
9200 assert!(updates.update_fulfill_htlcs.is_empty());
9201 assert_eq!(updates.update_fail_htlcs.len(), 1);
9202 assert!(updates.update_fail_malformed_htlcs.is_empty());
9203 assert!(updates.update_fee.is_none());
9204 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9205 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9206 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9211 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9212 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9213 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9216 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9217 let chanmon_cfgs = create_chanmon_cfgs(2);
9218 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9219 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9220 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9222 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9224 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9225 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9226 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9228 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9231 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9232 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9233 check_added_monitors!(nodes[0], 1);
9234 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9235 assert_eq!(events.len(), 1);
9236 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9237 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9238 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9240 expect_pending_htlcs_forwardable!(nodes[1]);
9241 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9244 // Note that we use a different PaymentId here to allow us to duplicativly pay
9245 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9246 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9247 check_added_monitors!(nodes[0], 1);
9248 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9249 assert_eq!(events.len(), 1);
9250 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9251 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9252 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9253 // At this point, nodes[1] would notice it has too much value for the payment. It will
9254 // assume the second is a privacy attack (no longer particularly relevant
9255 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9256 // the first HTLC delivered above.
9259 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9260 nodes[1].node.process_pending_htlc_forwards();
9262 if test_for_second_fail_panic {
9263 // Now we go fail back the first HTLC from the user end.
9264 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9266 let expected_destinations = vec![
9267 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9268 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9270 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9271 nodes[1].node.process_pending_htlc_forwards();
9273 check_added_monitors!(nodes[1], 1);
9274 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9275 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9277 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9278 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9279 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9281 let failure_events = nodes[0].node.get_and_clear_pending_events();
9282 assert_eq!(failure_events.len(), 4);
9283 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9284 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9285 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9286 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9288 // Let the second HTLC fail and claim the first
9289 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9290 nodes[1].node.process_pending_htlc_forwards();
9292 check_added_monitors!(nodes[1], 1);
9293 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9294 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9295 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9297 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9299 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9304 fn test_dup_htlc_second_fail_panic() {
9305 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9306 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9307 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9308 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9309 do_test_dup_htlc_second_rejected(true);
9313 fn test_dup_htlc_second_rejected() {
9314 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9315 // simply reject the second HTLC but are still able to claim the first HTLC.
9316 do_test_dup_htlc_second_rejected(false);
9320 fn test_inconsistent_mpp_params() {
9321 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9322 // such HTLC and allow the second to stay.
9323 let chanmon_cfgs = create_chanmon_cfgs(4);
9324 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9325 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9326 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9328 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9329 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9330 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9331 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9333 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9334 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9335 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9336 assert_eq!(route.paths.len(), 2);
9337 route.paths.sort_by(|path_a, _| {
9338 // Sort the path so that the path through nodes[1] comes first
9339 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9340 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9343 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9345 let cur_height = nodes[0].best_block_info().1;
9346 let payment_id = PaymentId([42; 32]);
9348 let session_privs = {
9349 // We create a fake route here so that we start with three pending HTLCs, which we'll
9350 // ultimately have, just not right away.
9351 let mut dup_route = route.clone();
9352 dup_route.paths.push(route.paths[1].clone());
9353 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9354 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9356 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9357 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9358 &None, session_privs[0]).unwrap();
9359 check_added_monitors!(nodes[0], 1);
9362 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9363 assert_eq!(events.len(), 1);
9364 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9366 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9368 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9369 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9370 check_added_monitors!(nodes[0], 1);
9373 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9374 assert_eq!(events.len(), 1);
9375 let payment_event = SendEvent::from_event(events.pop().unwrap());
9377 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9378 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9380 expect_pending_htlcs_forwardable!(nodes[2]);
9381 check_added_monitors!(nodes[2], 1);
9383 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9384 assert_eq!(events.len(), 1);
9385 let payment_event = SendEvent::from_event(events.pop().unwrap());
9387 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9388 check_added_monitors!(nodes[3], 0);
9389 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9391 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9392 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9393 // post-payment_secrets) and fail back the new HTLC.
9395 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9396 nodes[3].node.process_pending_htlc_forwards();
9397 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9398 nodes[3].node.process_pending_htlc_forwards();
9400 check_added_monitors!(nodes[3], 1);
9402 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9403 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9404 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9406 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 }]);
9407 check_added_monitors!(nodes[2], 1);
9409 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9410 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9411 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9413 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9415 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9416 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9417 &None, session_privs[2]).unwrap();
9418 check_added_monitors!(nodes[0], 1);
9420 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9421 assert_eq!(events.len(), 1);
9422 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9424 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9425 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9429 fn test_keysend_payments_to_public_node() {
9430 let chanmon_cfgs = create_chanmon_cfgs(2);
9431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9433 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9435 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9436 let network_graph = nodes[0].network_graph.clone();
9437 let payer_pubkey = nodes[0].node.get_our_node_id();
9438 let payee_pubkey = nodes[1].node.get_our_node_id();
9439 let route_params = RouteParameters {
9440 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9441 final_value_msat: 10000,
9443 let scorer = test_utils::TestScorer::new();
9444 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9445 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9447 let test_preimage = PaymentPreimage([42; 32]);
9448 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9449 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9450 check_added_monitors!(nodes[0], 1);
9451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9452 assert_eq!(events.len(), 1);
9453 let event = events.pop().unwrap();
9454 let path = vec![&nodes[1]];
9455 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9456 claim_payment(&nodes[0], &path, test_preimage);
9460 fn test_keysend_payments_to_private_node() {
9461 let chanmon_cfgs = create_chanmon_cfgs(2);
9462 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9463 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9464 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9466 let payer_pubkey = nodes[0].node.get_our_node_id();
9467 let payee_pubkey = nodes[1].node.get_our_node_id();
9469 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9470 let route_params = RouteParameters {
9471 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9472 final_value_msat: 10000,
9474 let network_graph = nodes[0].network_graph.clone();
9475 let first_hops = nodes[0].node.list_usable_channels();
9476 let scorer = test_utils::TestScorer::new();
9477 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9478 let route = find_route(
9479 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9480 nodes[0].logger, &scorer, &(), &random_seed_bytes
9483 let test_preimage = PaymentPreimage([42; 32]);
9484 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9485 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9486 check_added_monitors!(nodes[0], 1);
9487 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9488 assert_eq!(events.len(), 1);
9489 let event = events.pop().unwrap();
9490 let path = vec![&nodes[1]];
9491 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9492 claim_payment(&nodes[0], &path, test_preimage);
9496 fn test_double_partial_claim() {
9497 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9498 // time out, the sender resends only some of the MPP parts, then the user processes the
9499 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9501 let chanmon_cfgs = create_chanmon_cfgs(4);
9502 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9503 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9504 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9506 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9507 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9508 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9509 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9511 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9512 assert_eq!(route.paths.len(), 2);
9513 route.paths.sort_by(|path_a, _| {
9514 // Sort the path so that the path through nodes[1] comes first
9515 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9516 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9519 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9520 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9521 // amount of time to respond to.
9523 // Connect some blocks to time out the payment
9524 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9525 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9527 let failed_destinations = vec![
9528 HTLCDestination::FailedPayment { payment_hash },
9529 HTLCDestination::FailedPayment { payment_hash },
9531 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9533 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9535 // nodes[1] now retries one of the two paths...
9536 nodes[0].node.send_payment_with_route(&route, payment_hash,
9537 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9538 check_added_monitors!(nodes[0], 2);
9540 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9541 assert_eq!(events.len(), 2);
9542 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9543 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9545 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9546 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9547 nodes[3].node.claim_funds(payment_preimage);
9548 check_added_monitors!(nodes[3], 0);
9549 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9552 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9553 #[derive(Clone, Copy, PartialEq)]
9554 enum ExposureEvent {
9555 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9557 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9559 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9560 AtUpdateFeeOutbound,
9563 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9564 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9567 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9568 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9569 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9570 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9571 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9572 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9573 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9574 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9576 let chanmon_cfgs = create_chanmon_cfgs(2);
9577 let mut config = test_default_channel_config();
9578 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9581 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9583 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9584 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9585 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9586 open_channel.max_accepted_htlcs = 60;
9588 open_channel.dust_limit_satoshis = 546;
9590 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9591 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9592 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9594 let opt_anchors = false;
9596 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9599 let mut node_0_per_peer_lock;
9600 let mut node_0_peer_state_lock;
9601 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9602 chan.holder_dust_limit_satoshis = 546;
9605 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9606 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()));
9607 check_added_monitors!(nodes[1], 1);
9608 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9610 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()));
9611 check_added_monitors!(nodes[0], 1);
9612 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9614 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9615 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9616 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9618 let dust_buffer_feerate = {
9619 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9620 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9621 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9622 chan.get_dust_buffer_feerate(None) as u64
9624 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;
9625 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9627 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;
9628 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9630 let dust_htlc_on_counterparty_tx: u64 = 25;
9631 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9634 if dust_outbound_balance {
9635 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9636 // Outbound dust balance: 4372 sats
9637 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9638 for _ in 0..dust_outbound_htlc_on_holder_tx {
9639 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9640 nodes[0].node.send_payment_with_route(&route, payment_hash,
9641 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9644 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9645 // Inbound dust balance: 4372 sats
9646 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9647 for _ in 0..dust_inbound_htlc_on_holder_tx {
9648 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9652 if dust_outbound_balance {
9653 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9654 // Outbound dust balance: 5000 sats
9655 for _ in 0..dust_htlc_on_counterparty_tx {
9656 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9657 nodes[0].node.send_payment_with_route(&route, payment_hash,
9658 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9661 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9662 // Inbound dust balance: 5000 sats
9663 for _ in 0..dust_htlc_on_counterparty_tx {
9664 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9669 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9670 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9671 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 });
9672 let mut config = UserConfig::default();
9673 // With default dust exposure: 5000 sats
9675 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9676 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9677 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9678 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9679 ), true, APIError::ChannelUnavailable { ref err },
9680 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)));
9682 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9683 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9684 ), true, APIError::ChannelUnavailable { ref err },
9685 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)));
9687 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9688 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 });
9689 nodes[1].node.send_payment_with_route(&route, payment_hash,
9690 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9691 check_added_monitors!(nodes[1], 1);
9692 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9693 assert_eq!(events.len(), 1);
9694 let payment_event = SendEvent::from_event(events.remove(0));
9695 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9696 // With default dust exposure: 5000 sats
9698 // Outbound dust balance: 6399 sats
9699 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9700 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9701 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);
9703 // Outbound dust balance: 5200 sats
9704 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);
9706 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9707 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9708 nodes[0].node.send_payment_with_route(&route, payment_hash,
9709 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9711 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9712 *feerate_lock = *feerate_lock * 10;
9714 nodes[0].node.timer_tick_occurred();
9715 check_added_monitors!(nodes[0], 1);
9716 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9719 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9720 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9721 added_monitors.clear();
9725 fn test_max_dust_htlc_exposure() {
9726 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9727 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9728 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9729 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9730 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9731 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9732 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9733 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9734 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9735 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9736 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9737 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9741 fn test_non_final_funding_tx() {
9742 let chanmon_cfgs = create_chanmon_cfgs(2);
9743 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9744 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9745 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9747 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9748 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9749 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9750 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9751 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9753 let best_height = nodes[0].node.best_block.read().unwrap().height();
9755 let chan_id = *nodes[0].network_chan_count.borrow();
9756 let events = nodes[0].node.get_and_clear_pending_events();
9757 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9758 assert_eq!(events.len(), 1);
9759 let mut tx = match events[0] {
9760 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9761 // Timelock the transaction _beyond_ the best client height + 1.
9762 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9763 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9766 _ => panic!("Unexpected event"),
9768 // Transaction should fail as it's evaluated as non-final for propagation.
9769 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9770 Err(APIError::APIMisuseError { err }) => {
9771 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9776 // However, transaction should be accepted if it's in a +1 headroom from best block.
9777 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9778 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9779 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9783 fn accept_busted_but_better_fee() {
9784 // If a peer sends us a fee update that is too low, but higher than our previous channel
9785 // feerate, we should accept it. In the future we may want to consider closing the channel
9786 // later, but for now we only accept the update.
9787 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9792 create_chan_between_nodes(&nodes[0], &nodes[1]);
9794 // Set nodes[1] to expect 5,000 sat/kW.
9796 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9797 *feerate_lock = 5000;
9800 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9802 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9803 *feerate_lock = 1000;
9805 nodes[0].node.timer_tick_occurred();
9806 check_added_monitors!(nodes[0], 1);
9808 let events = nodes[0].node.get_and_clear_pending_msg_events();
9809 assert_eq!(events.len(), 1);
9811 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9812 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9813 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9815 _ => panic!("Unexpected event"),
9818 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9821 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9822 *feerate_lock = 2000;
9824 nodes[0].node.timer_tick_occurred();
9825 check_added_monitors!(nodes[0], 1);
9827 let events = nodes[0].node.get_and_clear_pending_msg_events();
9828 assert_eq!(events.len(), 1);
9830 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9831 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9832 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9834 _ => panic!("Unexpected event"),
9837 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9840 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9841 *feerate_lock = 1000;
9843 nodes[0].node.timer_tick_occurred();
9844 check_added_monitors!(nodes[0], 1);
9846 let events = nodes[0].node.get_and_clear_pending_msg_events();
9847 assert_eq!(events.len(), 1);
9849 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9850 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9851 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9852 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9853 check_closed_broadcast!(nodes[1], true);
9854 check_added_monitors!(nodes[1], 1);
9856 _ => panic!("Unexpected event"),
9860 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9861 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9864 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9865 let min_final_cltv_expiry_delta = 120;
9866 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9867 min_final_cltv_expiry_delta - 2 };
9868 let recv_value = 100_000;
9870 create_chan_between_nodes(&nodes[0], &nodes[1]);
9872 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9873 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9874 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9875 Some(recv_value), Some(min_final_cltv_expiry_delta));
9876 (payment_hash, payment_preimage, payment_secret)
9878 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9879 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9881 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9882 nodes[0].node.send_payment_with_route(&route, payment_hash,
9883 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9884 check_added_monitors!(nodes[0], 1);
9885 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9886 assert_eq!(events.len(), 1);
9887 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9889 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9890 expect_pending_htlcs_forwardable!(nodes[1]);
9893 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9894 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9896 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9898 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9900 check_added_monitors!(nodes[1], 1);
9902 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9903 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9904 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9906 expect_payment_failed!(nodes[0], payment_hash, true);
9911 fn test_payment_with_custom_min_cltv_expiry_delta() {
9912 do_payment_with_custom_min_final_cltv_expiry(false, false);
9913 do_payment_with_custom_min_final_cltv_expiry(false, true);
9914 do_payment_with_custom_min_final_cltv_expiry(true, false);
9915 do_payment_with_custom_min_final_cltv_expiry(true, true);