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::chain::keysinterface::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination};
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, BREAKDOWN_TIMEOUT, 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::{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::block::{Block, BlockHeader};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxMerkleNode, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex};
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
66 fn test_insane_channel_opens() {
67 // Stand up a network of 2 nodes
68 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
69 let mut cfg = UserConfig::default();
70 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
71 let chanmon_cfgs = create_chanmon_cfgs(2);
72 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
73 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
74 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
76 // Instantiate channel parameters where we push the maximum msats given our
78 let channel_value_sat = 31337; // same as funding satoshis
79 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
80 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
82 // Have node0 initiate a channel to node1 with aforementioned parameters
83 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
85 // Extract the channel open message from node0 to node1
86 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
88 // Test helper that asserts we get the correct error string given a mutator
89 // that supposedly makes the channel open message insane
90 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
91 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
92 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
93 assert_eq!(msg_events.len(), 1);
94 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
95 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
97 &ErrorAction::SendErrorMessage { .. } => {
98 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
100 _ => panic!("unexpected event!"),
102 } else { assert!(false); }
105 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
107 // Test all mutations that would make the channel open message insane
108 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 });
109 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 });
111 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
113 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 });
115 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
117 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 });
119 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 });
121 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
123 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
127 fn test_funding_exceeds_no_wumbo_limit() {
128 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
130 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
131 let chanmon_cfgs = create_chanmon_cfgs(2);
132 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
133 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
135 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
137 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
138 Err(APIError::APIMisuseError { err }) => {
139 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
145 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
146 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
147 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
148 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
149 // in normal testing, we test it explicitly here.
150 let chanmon_cfgs = create_chanmon_cfgs(2);
151 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
152 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
153 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
154 let default_config = UserConfig::default();
156 // Have node0 initiate a channel to node1 with aforementioned parameters
157 let mut push_amt = 100_000_000;
158 let feerate_per_kw = 253;
159 let opt_anchors = false;
160 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
161 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
163 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();
164 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
165 if !send_from_initiator {
166 open_channel_message.channel_reserve_satoshis = 0;
167 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
169 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
171 // Extract the channel accept message from node1 to node0
172 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
173 if send_from_initiator {
174 accept_channel_message.channel_reserve_satoshis = 0;
175 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
177 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
179 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
180 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
181 let mut sender_node_per_peer_lock;
182 let mut sender_node_peer_state_lock;
183 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184 chan.holder_selected_channel_reserve_satoshis = 0;
185 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
188 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
189 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
190 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
192 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
193 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
194 if send_from_initiator {
195 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
196 // Note that for outbound channels we have to consider the commitment tx fee and the
197 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
198 // well as an additional HTLC.
199 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
201 send_payment(&nodes[1], &[&nodes[0]], push_amt);
206 fn test_counterparty_no_reserve() {
207 do_test_counterparty_no_reserve(true);
208 do_test_counterparty_no_reserve(false);
212 fn test_async_inbound_update_fee() {
213 let chanmon_cfgs = create_chanmon_cfgs(2);
214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
216 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
217 create_announced_chan_between_nodes(&nodes, 0, 1);
220 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
224 // send (1) commitment_signed -.
225 // <- update_add_htlc/commitment_signed
226 // send (2) RAA (awaiting remote revoke) -.
227 // (1) commitment_signed is delivered ->
228 // .- send (3) RAA (awaiting remote revoke)
229 // (2) RAA is delivered ->
230 // .- send (4) commitment_signed
231 // <- (3) RAA is delivered
232 // send (5) commitment_signed -.
233 // <- (4) commitment_signed is delivered
235 // (5) commitment_signed is delivered ->
237 // (6) RAA is delivered ->
239 // First nodes[0] generates an update_fee
241 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
244 nodes[0].node.timer_tick_occurred();
245 check_added_monitors!(nodes[0], 1);
247 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
248 assert_eq!(events_0.len(), 1);
249 let (update_msg, commitment_signed) = match events_0[0] { // (1)
250 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
251 (update_fee.as_ref(), commitment_signed)
253 _ => panic!("Unexpected event"),
256 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
258 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
259 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
260 nodes[1].node.send_payment(&route, our_payment_hash, &Some(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(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
360 check_added_monitors!(nodes[1], 1);
362 let payment_event = {
363 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
364 assert_eq!(events_1.len(), 1);
365 SendEvent::from_event(events_1.remove(0))
367 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
368 assert_eq!(payment_event.msgs.len(), 1);
370 // ...now when the messages get delivered everyone should be happy
371 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
372 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
373 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
374 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
375 check_added_monitors!(nodes[0], 1);
377 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
378 check_added_monitors!(nodes[1], 1);
380 // We can't continue, sadly, because our (1) now has a bogus signature
384 fn test_multi_flight_update_fee() {
385 let chanmon_cfgs = create_chanmon_cfgs(2);
386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
389 create_announced_chan_between_nodes(&nodes, 0, 1);
392 // update_fee/commitment_signed ->
393 // .- send (1) RAA and (2) commitment_signed
394 // update_fee (never committed) ->
396 // We have to manually generate the above update_fee, it is allowed by the protocol but we
397 // don't track which updates correspond to which revoke_and_ack responses so we're in
398 // AwaitingRAA mode and will not generate the update_fee yet.
399 // <- (1) RAA delivered
400 // (3) is generated and send (4) CS -.
401 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
402 // know the per_commitment_point to use for it.
403 // <- (2) commitment_signed delivered
405 // B should send no response here
406 // (4) commitment_signed delivered ->
407 // <- RAA/commitment_signed delivered
410 // First nodes[0] generates an update_fee
413 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
414 initial_feerate = *feerate_lock;
415 *feerate_lock = initial_feerate + 20;
417 nodes[0].node.timer_tick_occurred();
418 check_added_monitors!(nodes[0], 1);
420 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
421 assert_eq!(events_0.len(), 1);
422 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
423 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
424 (update_fee.as_ref().unwrap(), commitment_signed)
426 _ => panic!("Unexpected event"),
429 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
430 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
431 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
432 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
433 check_added_monitors!(nodes[1], 1);
435 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
438 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
439 *feerate_lock = initial_feerate + 40;
441 nodes[0].node.timer_tick_occurred();
442 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
443 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
445 // Create the (3) update_fee message that nodes[0] will generate before it does...
446 let mut update_msg_2 = msgs::UpdateFee {
447 channel_id: update_msg_1.channel_id.clone(),
448 feerate_per_kw: (initial_feerate + 30) as u32,
451 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
453 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
455 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
457 // Deliver (1), generating (3) and (4)
458 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
459 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
460 check_added_monitors!(nodes[0], 1);
461 assert!(as_second_update.update_add_htlcs.is_empty());
462 assert!(as_second_update.update_fulfill_htlcs.is_empty());
463 assert!(as_second_update.update_fail_htlcs.is_empty());
464 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
465 // Check that the update_fee newly generated matches what we delivered:
466 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
467 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
469 // Deliver (2) commitment_signed
470 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
471 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
472 check_added_monitors!(nodes[0], 1);
473 // No commitment_signed so get_event_msg's assert(len == 1) passes
475 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
476 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
477 check_added_monitors!(nodes[1], 1);
480 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
481 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
482 check_added_monitors!(nodes[1], 1);
484 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
485 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
486 check_added_monitors!(nodes[0], 1);
488 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
489 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
490 // No commitment_signed so get_event_msg's assert(len == 1) passes
491 check_added_monitors!(nodes[0], 1);
493 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
494 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
495 check_added_monitors!(nodes[1], 1);
498 fn do_test_sanity_on_in_flight_opens(steps: u8) {
499 // Previously, we had issues deserializing channels when we hadn't connected the first block
500 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
501 // serialization round-trips and simply do steps towards opening a channel and then drop the
504 let chanmon_cfgs = create_chanmon_cfgs(2);
505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
507 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
509 if steps & 0b1000_0000 != 0{
511 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
514 connect_block(&nodes[0], &block);
515 connect_block(&nodes[1], &block);
518 if steps & 0x0f == 0 { return; }
519 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
520 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
522 if steps & 0x0f == 1 { return; }
523 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
524 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
526 if steps & 0x0f == 2 { return; }
527 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
529 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
531 if steps & 0x0f == 3 { return; }
532 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
533 check_added_monitors!(nodes[0], 0);
534 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
536 if steps & 0x0f == 4 { return; }
537 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
539 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
540 assert_eq!(added_monitors.len(), 1);
541 assert_eq!(added_monitors[0].0, funding_output);
542 added_monitors.clear();
544 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
546 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
548 if steps & 0x0f == 5 { return; }
549 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
551 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
552 assert_eq!(added_monitors.len(), 1);
553 assert_eq!(added_monitors[0].0, funding_output);
554 added_monitors.clear();
557 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
558 let events_4 = nodes[0].node.get_and_clear_pending_events();
559 assert_eq!(events_4.len(), 0);
561 if steps & 0x0f == 6 { return; }
562 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
564 if steps & 0x0f == 7 { return; }
565 confirm_transaction_at(&nodes[0], &tx, 2);
566 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
567 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
568 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
572 fn test_sanity_on_in_flight_opens() {
573 do_test_sanity_on_in_flight_opens(0);
574 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(1);
576 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(2);
578 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(3);
580 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(4);
582 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(5);
584 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(6);
586 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(7);
588 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
589 do_test_sanity_on_in_flight_opens(8);
590 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
594 fn test_update_fee_vanilla() {
595 let chanmon_cfgs = create_chanmon_cfgs(2);
596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
598 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
599 create_announced_chan_between_nodes(&nodes, 0, 1);
602 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
605 nodes[0].node.timer_tick_occurred();
606 check_added_monitors!(nodes[0], 1);
608 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
609 assert_eq!(events_0.len(), 1);
610 let (update_msg, commitment_signed) = match events_0[0] {
611 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 } } => {
612 (update_fee.as_ref(), commitment_signed)
614 _ => panic!("Unexpected event"),
616 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
618 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
619 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
620 check_added_monitors!(nodes[1], 1);
622 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
623 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
624 check_added_monitors!(nodes[0], 1);
626 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
627 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
628 // No commitment_signed so get_event_msg's assert(len == 1) passes
629 check_added_monitors!(nodes[0], 1);
631 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
632 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
633 check_added_monitors!(nodes[1], 1);
637 fn test_update_fee_that_funder_cannot_afford() {
638 let chanmon_cfgs = create_chanmon_cfgs(2);
639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
642 let channel_value = 5000;
644 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
645 let channel_id = chan.2;
646 let secp_ctx = Secp256k1::new();
647 let default_config = UserConfig::default();
648 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
650 let opt_anchors = false;
652 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
653 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
654 // calculate two different feerates here - the expected local limit as well as the expected
656 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;
657 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
659 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
660 *feerate_lock = feerate;
662 nodes[0].node.timer_tick_occurred();
663 check_added_monitors!(nodes[0], 1);
664 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
666 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
668 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
670 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
672 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
674 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
675 assert_eq!(commitment_tx.output.len(), 2);
676 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
677 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
678 actual_fee = channel_value - actual_fee;
679 assert_eq!(total_fee, actual_fee);
683 // Increment the feerate by a small constant, accounting for rounding errors
684 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
687 nodes[0].node.timer_tick_occurred();
688 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
689 check_added_monitors!(nodes[0], 0);
691 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
693 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
694 // needed to sign the new commitment tx and (2) sign the new commitment tx.
695 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
696 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
697 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
698 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
699 let chan_signer = local_chan.get_signer();
700 let pubkeys = chan_signer.pubkeys();
701 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
702 pubkeys.funding_pubkey)
704 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
705 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
706 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
707 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
708 let chan_signer = remote_chan.get_signer();
709 let pubkeys = chan_signer.pubkeys();
710 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
711 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
712 pubkeys.funding_pubkey)
715 // Assemble the set of keys we can use for signatures for our commitment_signed message.
716 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
717 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
720 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
721 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
722 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
723 let local_chan_signer = local_chan.get_signer();
724 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
725 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
726 INITIAL_COMMITMENT_NUMBER - 1,
728 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
729 opt_anchors, local_funding, remote_funding,
730 commit_tx_keys.clone(),
731 non_buffer_feerate + 4,
733 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
735 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
738 let commit_signed_msg = msgs::CommitmentSigned {
741 htlc_signatures: res.1,
743 partial_signature_with_nonce: None,
746 let update_fee = msgs::UpdateFee {
748 feerate_per_kw: non_buffer_feerate + 4,
751 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
753 //While producing the commitment_signed response after handling a received update_fee request the
754 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
755 //Should produce and error.
756 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
757 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
758 check_added_monitors!(nodes[1], 1);
759 check_closed_broadcast!(nodes[1], true);
760 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
764 fn test_update_fee_with_fundee_update_add_htlc() {
765 let chanmon_cfgs = create_chanmon_cfgs(2);
766 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
767 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
768 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
769 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
772 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
775 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
778 nodes[0].node.timer_tick_occurred();
779 check_added_monitors!(nodes[0], 1);
781 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
782 assert_eq!(events_0.len(), 1);
783 let (update_msg, commitment_signed) = match events_0[0] {
784 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 } } => {
785 (update_fee.as_ref(), commitment_signed)
787 _ => panic!("Unexpected event"),
789 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
790 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
791 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
792 check_added_monitors!(nodes[1], 1);
794 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
796 // nothing happens since node[1] is in AwaitingRemoteRevoke
797 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
799 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
800 assert_eq!(added_monitors.len(), 0);
801 added_monitors.clear();
803 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
804 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
805 // node[1] has nothing to do
807 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
808 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
809 check_added_monitors!(nodes[0], 1);
811 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
812 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
813 // No commitment_signed so get_event_msg's assert(len == 1) passes
814 check_added_monitors!(nodes[0], 1);
815 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
816 check_added_monitors!(nodes[1], 1);
817 // AwaitingRemoteRevoke ends here
819 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
820 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
821 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
824 assert_eq!(commitment_update.update_fee.is_none(), true);
826 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
827 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
828 check_added_monitors!(nodes[0], 1);
829 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
831 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
832 check_added_monitors!(nodes[1], 1);
833 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
835 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
836 check_added_monitors!(nodes[1], 1);
837 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
838 // No commitment_signed so get_event_msg's assert(len == 1) passes
840 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
841 check_added_monitors!(nodes[0], 1);
842 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
844 expect_pending_htlcs_forwardable!(nodes[0]);
846 let events = nodes[0].node.get_and_clear_pending_events();
847 assert_eq!(events.len(), 1);
849 Event::PaymentClaimable { .. } => { },
850 _ => panic!("Unexpected event"),
853 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
855 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
856 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
857 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
858 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
859 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
863 fn test_update_fee() {
864 let chanmon_cfgs = create_chanmon_cfgs(2);
865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
868 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
869 let channel_id = chan.2;
872 // (1) update_fee/commitment_signed ->
873 // <- (2) revoke_and_ack
874 // .- send (3) commitment_signed
875 // (4) update_fee/commitment_signed ->
876 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
877 // <- (3) commitment_signed delivered
878 // send (6) revoke_and_ack -.
879 // <- (5) deliver revoke_and_ack
880 // (6) deliver revoke_and_ack ->
881 // .- send (7) commitment_signed in response to (4)
882 // <- (7) deliver commitment_signed
885 // Create and deliver (1)...
888 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
889 feerate = *feerate_lock;
890 *feerate_lock = feerate + 20;
892 nodes[0].node.timer_tick_occurred();
893 check_added_monitors!(nodes[0], 1);
895 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
896 assert_eq!(events_0.len(), 1);
897 let (update_msg, commitment_signed) = match events_0[0] {
898 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 } } => {
899 (update_fee.as_ref(), commitment_signed)
901 _ => panic!("Unexpected event"),
903 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
905 // Generate (2) and (3):
906 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
907 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
908 check_added_monitors!(nodes[1], 1);
911 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
912 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
913 check_added_monitors!(nodes[0], 1);
915 // Create and deliver (4)...
917 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
918 *feerate_lock = feerate + 30;
920 nodes[0].node.timer_tick_occurred();
921 check_added_monitors!(nodes[0], 1);
922 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
923 assert_eq!(events_0.len(), 1);
924 let (update_msg, commitment_signed) = match events_0[0] {
925 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 } } => {
926 (update_fee.as_ref(), commitment_signed)
928 _ => panic!("Unexpected event"),
931 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
932 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
933 check_added_monitors!(nodes[1], 1);
935 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
936 // No commitment_signed so get_event_msg's assert(len == 1) passes
938 // Handle (3), creating (6):
939 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
940 check_added_monitors!(nodes[0], 1);
941 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
942 // No commitment_signed so get_event_msg's assert(len == 1) passes
945 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
946 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
947 check_added_monitors!(nodes[0], 1);
949 // Deliver (6), creating (7):
950 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
951 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
952 assert!(commitment_update.update_add_htlcs.is_empty());
953 assert!(commitment_update.update_fulfill_htlcs.is_empty());
954 assert!(commitment_update.update_fail_htlcs.is_empty());
955 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
956 assert!(commitment_update.update_fee.is_none());
957 check_added_monitors!(nodes[1], 1);
960 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
961 check_added_monitors!(nodes[0], 1);
962 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
963 // No commitment_signed so get_event_msg's assert(len == 1) passes
965 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
966 check_added_monitors!(nodes[1], 1);
967 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
969 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
970 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
971 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
972 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
973 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
977 fn fake_network_test() {
978 // Simple test which builds a network of ChannelManagers, connects them to each other, and
979 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
980 let chanmon_cfgs = create_chanmon_cfgs(4);
981 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
982 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
983 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
985 // Create some initial channels
986 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
987 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
988 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
990 // Rebalance the network a bit by relaying one payment through all the channels...
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);
994 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
996 // Send some more payments
997 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
999 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1001 // Test failure packets
1002 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1003 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1005 // Add a new channel that skips 3
1006 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1008 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1009 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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);
1014 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1016 // Do some rebalance loop payments, simultaneously
1017 let mut hops = Vec::with_capacity(3);
1018 hops.push(RouteHop {
1019 pubkey: nodes[2].node.get_our_node_id(),
1020 node_features: NodeFeatures::empty(),
1021 short_channel_id: chan_2.0.contents.short_channel_id,
1022 channel_features: ChannelFeatures::empty(),
1024 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1026 hops.push(RouteHop {
1027 pubkey: nodes[3].node.get_our_node_id(),
1028 node_features: NodeFeatures::empty(),
1029 short_channel_id: chan_3.0.contents.short_channel_id,
1030 channel_features: ChannelFeatures::empty(),
1032 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1034 hops.push(RouteHop {
1035 pubkey: nodes[1].node.get_our_node_id(),
1036 node_features: nodes[1].node.node_features(),
1037 short_channel_id: chan_4.0.contents.short_channel_id,
1038 channel_features: nodes[1].node.channel_features(),
1040 cltv_expiry_delta: TEST_FINAL_CLTV,
1042 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;
1043 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;
1044 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1046 let mut hops = Vec::with_capacity(3);
1047 hops.push(RouteHop {
1048 pubkey: nodes[3].node.get_our_node_id(),
1049 node_features: NodeFeatures::empty(),
1050 short_channel_id: chan_4.0.contents.short_channel_id,
1051 channel_features: ChannelFeatures::empty(),
1053 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1055 hops.push(RouteHop {
1056 pubkey: nodes[2].node.get_our_node_id(),
1057 node_features: NodeFeatures::empty(),
1058 short_channel_id: chan_3.0.contents.short_channel_id,
1059 channel_features: ChannelFeatures::empty(),
1061 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1063 hops.push(RouteHop {
1064 pubkey: nodes[1].node.get_our_node_id(),
1065 node_features: nodes[1].node.node_features(),
1066 short_channel_id: chan_2.0.contents.short_channel_id,
1067 channel_features: nodes[1].node.channel_features(),
1069 cltv_expiry_delta: TEST_FINAL_CLTV,
1071 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;
1072 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;
1073 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1075 // Claim the rebalances...
1076 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1077 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1079 // Close down the channels...
1080 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1081 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1082 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1083 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1084 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1085 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1086 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1087 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1088 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1089 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1090 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1091 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1095 fn holding_cell_htlc_counting() {
1096 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1097 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1098 // commitment dance rounds.
1099 let chanmon_cfgs = create_chanmon_cfgs(3);
1100 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1101 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1102 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1103 create_announced_chan_between_nodes(&nodes, 0, 1);
1104 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1106 let mut payments = Vec::new();
1107 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1108 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1109 nodes[1].node.send_payment(&route, payment_hash, &Some(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(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)), true, APIError::ChannelUnavailable { ref err },
1125 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1126 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1127 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1130 // This should also be true if we try to forward a payment.
1131 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1133 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1134 check_added_monitors!(nodes[0], 1);
1137 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1138 assert_eq!(events.len(), 1);
1139 let payment_event = SendEvent::from_event(events.pop().unwrap());
1140 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1142 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1143 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1144 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1145 // fails), the second will process the resulting failure and fail the HTLC backward.
1146 expect_pending_htlcs_forwardable!(nodes[1]);
1147 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 }]);
1148 check_added_monitors!(nodes[1], 1);
1150 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1151 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1152 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1154 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1156 // Now forward all the pending HTLCs and claim them back
1157 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1158 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1159 check_added_monitors!(nodes[2], 1);
1161 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1162 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1163 check_added_monitors!(nodes[1], 1);
1164 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1166 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1167 check_added_monitors!(nodes[1], 1);
1168 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1170 for ref update in as_updates.update_add_htlcs.iter() {
1171 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1173 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1174 check_added_monitors!(nodes[2], 1);
1175 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1176 check_added_monitors!(nodes[2], 1);
1177 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1179 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1180 check_added_monitors!(nodes[1], 1);
1181 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1182 check_added_monitors!(nodes[1], 1);
1183 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1185 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1186 check_added_monitors!(nodes[2], 1);
1188 expect_pending_htlcs_forwardable!(nodes[2]);
1190 let events = nodes[2].node.get_and_clear_pending_events();
1191 assert_eq!(events.len(), payments.len());
1192 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1194 &Event::PaymentClaimable { ref payment_hash, .. } => {
1195 assert_eq!(*payment_hash, *hash);
1197 _ => panic!("Unexpected event"),
1201 for (preimage, _) in payments.drain(..) {
1202 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1205 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1209 fn duplicate_htlc_test() {
1210 // Test that we accept duplicate payment_hash HTLCs across the network and that
1211 // claiming/failing them are all separate and don't affect each other
1212 let chanmon_cfgs = create_chanmon_cfgs(6);
1213 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1214 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1215 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1217 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1218 create_announced_chan_between_nodes(&nodes, 0, 3);
1219 create_announced_chan_between_nodes(&nodes, 1, 3);
1220 create_announced_chan_between_nodes(&nodes, 2, 3);
1221 create_announced_chan_between_nodes(&nodes, 3, 4);
1222 create_announced_chan_between_nodes(&nodes, 3, 5);
1224 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1226 *nodes[0].network_payment_count.borrow_mut() -= 1;
1227 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1232 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1233 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1234 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1238 fn test_duplicate_htlc_different_direction_onchain() {
1239 // Test that ChannelMonitor doesn't generate 2 preimage txn
1240 // when we have 2 HTLCs with same preimage that go across a node
1241 // in opposite directions, even with the same payment secret.
1242 let chanmon_cfgs = create_chanmon_cfgs(2);
1243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1245 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1247 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1250 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1252 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1254 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1255 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1256 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1258 // Provide preimage to node 0 by claiming payment
1259 nodes[0].node.claim_funds(payment_preimage);
1260 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1261 check_added_monitors!(nodes[0], 1);
1263 // Broadcast node 1 commitment txn
1264 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1266 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1267 let mut has_both_htlcs = 0; // check htlcs match ones committed
1268 for outp in remote_txn[0].output.iter() {
1269 if outp.value == 800_000 / 1000 {
1270 has_both_htlcs += 1;
1271 } else if outp.value == 900_000 / 1000 {
1272 has_both_htlcs += 1;
1275 assert_eq!(has_both_htlcs, 2);
1277 mine_transaction(&nodes[0], &remote_txn[0]);
1278 check_added_monitors!(nodes[0], 1);
1279 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1280 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1282 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1283 assert_eq!(claim_txn.len(), 3);
1285 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1286 check_spends!(claim_txn[1], remote_txn[0]);
1287 check_spends!(claim_txn[2], remote_txn[0]);
1288 let preimage_tx = &claim_txn[0];
1289 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1290 (&claim_txn[1], &claim_txn[2])
1292 (&claim_txn[2], &claim_txn[1])
1295 assert_eq!(preimage_tx.input.len(), 1);
1296 assert_eq!(preimage_bump_tx.input.len(), 1);
1298 assert_eq!(preimage_tx.input.len(), 1);
1299 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1300 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1302 assert_eq!(timeout_tx.input.len(), 1);
1303 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1304 check_spends!(timeout_tx, remote_txn[0]);
1305 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1307 let events = nodes[0].node.get_and_clear_pending_msg_events();
1308 assert_eq!(events.len(), 3);
1311 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1312 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1313 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1314 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1316 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, .. } } => {
1317 assert!(update_add_htlcs.is_empty());
1318 assert!(update_fail_htlcs.is_empty());
1319 assert_eq!(update_fulfill_htlcs.len(), 1);
1320 assert!(update_fail_malformed_htlcs.is_empty());
1321 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1323 _ => panic!("Unexpected event"),
1329 fn test_basic_channel_reserve() {
1330 let chanmon_cfgs = create_chanmon_cfgs(2);
1331 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1332 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1333 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1334 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1336 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1337 let channel_reserve = chan_stat.channel_reserve_msat;
1339 // The 2* and +1 are for the fee spike reserve.
1340 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));
1341 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1342 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1343 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1345 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1347 &APIError::ChannelUnavailable{ref err} =>
1348 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1349 _ => panic!("Unexpected error variant"),
1352 _ => panic!("Unexpected error variant"),
1354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1355 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1357 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1361 fn test_fee_spike_violation_fails_htlc() {
1362 let chanmon_cfgs = create_chanmon_cfgs(2);
1363 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1364 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1365 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1366 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1368 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1369 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1370 let secp_ctx = Secp256k1::new();
1371 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1373 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1375 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1376 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1377 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1378 let msg = msgs::UpdateAddHTLC {
1381 amount_msat: htlc_msat,
1382 payment_hash: payment_hash,
1383 cltv_expiry: htlc_cltv,
1384 onion_routing_packet: onion_packet,
1387 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1389 // Now manually create the commitment_signed message corresponding to the update_add
1390 // nodes[0] just sent. In the code for construction of this message, "local" refers
1391 // to the sender of the message, and "remote" refers to the receiver.
1393 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1395 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1397 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1398 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1399 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1400 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1401 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1402 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1403 let chan_signer = local_chan.get_signer();
1404 // Make the signer believe we validated another commitment, so we can release the secret
1405 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1407 let pubkeys = chan_signer.pubkeys();
1408 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1409 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1410 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1411 chan_signer.pubkeys().funding_pubkey)
1413 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1414 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1415 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1416 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1417 let chan_signer = remote_chan.get_signer();
1418 let pubkeys = chan_signer.pubkeys();
1419 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1420 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1421 chan_signer.pubkeys().funding_pubkey)
1424 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1425 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1426 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1428 // Build the remote commitment transaction so we can sign it, and then later use the
1429 // signature for the commitment_signed message.
1430 let local_chan_balance = 1313;
1432 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1434 amount_msat: 3460001,
1435 cltv_expiry: htlc_cltv,
1437 transaction_output_index: Some(1),
1440 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1443 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1444 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1445 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1446 let local_chan_signer = local_chan.get_signer();
1447 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1451 local_chan.opt_anchors(), local_funding, remote_funding,
1452 commit_tx_keys.clone(),
1454 &mut vec![(accepted_htlc_info, ())],
1455 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1457 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1460 let commit_signed_msg = msgs::CommitmentSigned {
1463 htlc_signatures: res.1,
1465 partial_signature_with_nonce: None,
1468 // Send the commitment_signed message to the nodes[1].
1469 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1470 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1472 // Send the RAA to nodes[1].
1473 let raa_msg = msgs::RevokeAndACK {
1475 per_commitment_secret: local_secret,
1476 next_per_commitment_point: next_local_point,
1478 next_local_nonce: None,
1480 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1482 let events = nodes[1].node.get_and_clear_pending_msg_events();
1483 assert_eq!(events.len(), 1);
1484 // Make sure the HTLC failed in the way we expect.
1486 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1487 assert_eq!(update_fail_htlcs.len(), 1);
1488 update_fail_htlcs[0].clone()
1490 _ => panic!("Unexpected event"),
1492 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1493 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1495 check_added_monitors!(nodes[1], 2);
1499 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1500 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1501 // Set the fee rate for the channel very high, to the point where the fundee
1502 // sending any above-dust amount would result in a channel reserve violation.
1503 // In this test we check that we would be prevented from sending an HTLC in
1505 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1508 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1509 let default_config = UserConfig::default();
1510 let opt_anchors = false;
1512 let mut push_amt = 100_000_000;
1513 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1515 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1517 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1519 // Sending exactly enough to hit the reserve amount should be accepted
1520 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1521 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1524 // However one more HTLC should be significantly over the reserve amount and fail.
1525 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1526 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1527 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1528 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1529 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);
1533 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1534 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1535 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1536 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1537 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1538 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1539 let default_config = UserConfig::default();
1540 let opt_anchors = false;
1542 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1543 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1544 // transaction fee with 0 HTLCs (183 sats)).
1545 let mut push_amt = 100_000_000;
1546 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1547 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1548 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1550 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1551 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1552 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1555 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1556 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1557 let secp_ctx = Secp256k1::new();
1558 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1559 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1560 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1561 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1562 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1563 let msg = msgs::UpdateAddHTLC {
1565 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1566 amount_msat: htlc_msat,
1567 payment_hash: payment_hash,
1568 cltv_expiry: htlc_cltv,
1569 onion_routing_packet: onion_packet,
1572 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1573 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1574 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);
1575 assert_eq!(nodes[0].node.list_channels().len(), 0);
1576 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1577 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1578 check_added_monitors!(nodes[0], 1);
1579 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() });
1583 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1584 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1585 // calculating our commitment transaction fee (this was previously broken).
1586 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1587 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1591 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1592 let default_config = UserConfig::default();
1593 let opt_anchors = false;
1595 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1596 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1597 // transaction fee with 0 HTLCs (183 sats)).
1598 let mut push_amt = 100_000_000;
1599 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1600 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1601 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1603 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1604 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1605 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1606 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1607 // commitment transaction fee.
1608 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1610 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1611 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1612 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1615 // One more than the dust amt should fail, however.
1616 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1617 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1618 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1622 fn test_chan_init_feerate_unaffordability() {
1623 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1624 // channel reserve and feerate requirements.
1625 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1626 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1629 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1630 let default_config = UserConfig::default();
1631 let opt_anchors = false;
1633 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1635 let mut push_amt = 100_000_000;
1636 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1637 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1638 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1640 // During open, we don't have a "counterparty channel reserve" to check against, so that
1641 // requirement only comes into play on the open_channel handling side.
1642 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1643 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1644 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1645 open_channel_msg.push_msat += 1;
1646 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1648 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1649 assert_eq!(msg_events.len(), 1);
1650 match msg_events[0] {
1651 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1652 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1654 _ => panic!("Unexpected event"),
1659 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1660 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1661 // calculating our counterparty's commitment transaction fee (this was previously broken).
1662 let chanmon_cfgs = create_chanmon_cfgs(2);
1663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1665 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1666 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1668 let payment_amt = 46000; // Dust amount
1669 // In the previous code, these first four payments would succeed.
1670 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1671 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1676 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1677 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1678 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1682 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1683 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1684 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1690 let chanmon_cfgs = create_chanmon_cfgs(3);
1691 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1692 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1693 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1694 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1695 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1698 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1699 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1700 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1701 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1703 // Add a 2* and +1 for the fee spike reserve.
1704 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1705 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;
1706 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1708 // Add a pending HTLC.
1709 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1710 let payment_event_1 = {
1711 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1712 check_added_monitors!(nodes[0], 1);
1714 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1715 assert_eq!(events.len(), 1);
1716 SendEvent::from_event(events.remove(0))
1718 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1720 // Attempt to trigger a channel reserve violation --> payment failure.
1721 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1722 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;
1723 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1724 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1726 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1727 let secp_ctx = Secp256k1::new();
1728 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1729 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1730 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1731 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1732 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1733 let msg = msgs::UpdateAddHTLC {
1736 amount_msat: htlc_msat + 1,
1737 payment_hash: our_payment_hash_1,
1738 cltv_expiry: htlc_cltv,
1739 onion_routing_packet: onion_packet,
1742 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1743 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1744 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1745 assert_eq!(nodes[1].node.list_channels().len(), 1);
1746 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1747 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1748 check_added_monitors!(nodes[1], 1);
1749 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1753 fn test_inbound_outbound_capacity_is_not_zero() {
1754 let chanmon_cfgs = create_chanmon_cfgs(2);
1755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1757 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1758 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1759 let channels0 = node_chanmgrs[0].list_channels();
1760 let channels1 = node_chanmgrs[1].list_channels();
1761 let default_config = UserConfig::default();
1762 assert_eq!(channels0.len(), 1);
1763 assert_eq!(channels1.len(), 1);
1765 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1766 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1767 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1769 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1770 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1773 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1774 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1778 fn test_channel_reserve_holding_cell_htlcs() {
1779 let chanmon_cfgs = create_chanmon_cfgs(3);
1780 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1781 // When this test was written, the default base fee floated based on the HTLC count.
1782 // It is now fixed, so we simply set the fee to the expected value here.
1783 let mut config = test_default_channel_config();
1784 config.channel_config.forwarding_fee_base_msat = 239;
1785 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1786 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1787 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1788 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1790 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1791 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1793 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1794 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1796 macro_rules! expect_forward {
1798 let mut events = $node.node.get_and_clear_pending_msg_events();
1799 assert_eq!(events.len(), 1);
1800 check_added_monitors!($node, 1);
1801 let payment_event = SendEvent::from_event(events.remove(0));
1806 let feemsat = 239; // set above
1807 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1808 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1809 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1811 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1813 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1815 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1816 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1817 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0, TEST_FINAL_CLTV);
1818 route.paths[0].last_mut().unwrap().fee_msat += 1;
1819 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1821 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1822 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)));
1823 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1824 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);
1827 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1828 // nodes[0]'s wealth
1830 let amt_msat = recv_value_0 + total_fee_msat;
1831 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1832 // Also, ensure that each payment has enough to be over the dust limit to
1833 // ensure it'll be included in each commit tx fee calculation.
1834 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1835 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1836 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1840 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1841 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1842 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1843 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1844 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1846 let (stat01_, stat11_, stat12_, stat22_) = (
1847 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1848 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1849 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1850 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1853 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1854 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1855 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1856 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1857 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1860 // adding pending output.
1861 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1862 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1863 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1864 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1865 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1866 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1867 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1868 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1869 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1871 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1872 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1873 let amt_msat_1 = recv_value_1 + total_fee_msat;
1875 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);
1876 let payment_event_1 = {
1877 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1878 check_added_monitors!(nodes[0], 1);
1880 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1881 assert_eq!(events.len(), 1);
1882 SendEvent::from_event(events.remove(0))
1884 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1886 // channel reserve test with htlc pending output > 0
1887 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1889 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1890 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1891 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1892 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1895 // split the rest to test holding cell
1896 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1897 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1898 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1899 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1901 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1902 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);
1905 // now see if they go through on both sides
1906 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);
1907 // but this will stuck in the holding cell
1908 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1909 check_added_monitors!(nodes[0], 0);
1910 let events = nodes[0].node.get_and_clear_pending_events();
1911 assert_eq!(events.len(), 0);
1913 // test with outbound holding cell amount > 0
1915 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1916 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
1917 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1918 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1919 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1922 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);
1923 // this will also stuck in the holding cell
1924 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1925 check_added_monitors!(nodes[0], 0);
1926 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1927 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1929 // flush the pending htlc
1930 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1931 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1932 check_added_monitors!(nodes[1], 1);
1934 // the pending htlc should be promoted to committed
1935 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1936 check_added_monitors!(nodes[0], 1);
1937 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1939 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1940 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1941 // No commitment_signed so get_event_msg's assert(len == 1) passes
1942 check_added_monitors!(nodes[0], 1);
1944 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1945 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1946 check_added_monitors!(nodes[1], 1);
1948 expect_pending_htlcs_forwardable!(nodes[1]);
1950 let ref payment_event_11 = expect_forward!(nodes[1]);
1951 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1952 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1954 expect_pending_htlcs_forwardable!(nodes[2]);
1955 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1957 // flush the htlcs in the holding cell
1958 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1959 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1961 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1962 expect_pending_htlcs_forwardable!(nodes[1]);
1964 let ref payment_event_3 = expect_forward!(nodes[1]);
1965 assert_eq!(payment_event_3.msgs.len(), 2);
1966 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1967 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1969 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1970 expect_pending_htlcs_forwardable!(nodes[2]);
1972 let events = nodes[2].node.get_and_clear_pending_events();
1973 assert_eq!(events.len(), 2);
1975 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1976 assert_eq!(our_payment_hash_21, *payment_hash);
1977 assert_eq!(recv_value_21, amount_msat);
1978 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1979 assert_eq!(via_channel_id, Some(chan_2.2));
1981 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1982 assert!(payment_preimage.is_none());
1983 assert_eq!(our_payment_secret_21, *payment_secret);
1985 _ => panic!("expected PaymentPurpose::InvoicePayment")
1988 _ => panic!("Unexpected event"),
1991 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1992 assert_eq!(our_payment_hash_22, *payment_hash);
1993 assert_eq!(recv_value_22, amount_msat);
1994 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1995 assert_eq!(via_channel_id, Some(chan_2.2));
1997 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1998 assert!(payment_preimage.is_none());
1999 assert_eq!(our_payment_secret_22, *payment_secret);
2001 _ => panic!("expected PaymentPurpose::InvoicePayment")
2004 _ => panic!("Unexpected event"),
2007 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2008 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2009 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2011 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2012 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2013 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2015 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2016 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);
2017 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2018 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2019 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2021 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2022 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2026 fn channel_reserve_in_flight_removes() {
2027 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2028 // can send to its counterparty, but due to update ordering, the other side may not yet have
2029 // considered those HTLCs fully removed.
2030 // This tests that we don't count HTLCs which will not be included in the next remote
2031 // commitment transaction towards the reserve value (as it implies no commitment transaction
2032 // will be generated which violates the remote reserve value).
2033 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2035 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2036 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2037 // you only consider the value of the first HTLC, it may not),
2038 // * start routing a third HTLC from A to B,
2039 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2040 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2041 // * deliver the first fulfill from B
2042 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2044 // * deliver A's response CS and RAA.
2045 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2046 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2047 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2048 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2049 let chanmon_cfgs = create_chanmon_cfgs(2);
2050 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2051 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2052 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2053 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2055 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2056 // Route the first two HTLCs.
2057 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2058 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2059 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2061 // Start routing the third HTLC (this is just used to get everyone in the right state).
2062 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2064 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2065 check_added_monitors!(nodes[0], 1);
2066 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2067 assert_eq!(events.len(), 1);
2068 SendEvent::from_event(events.remove(0))
2071 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2072 // initial fulfill/CS.
2073 nodes[1].node.claim_funds(payment_preimage_1);
2074 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2075 check_added_monitors!(nodes[1], 1);
2076 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2078 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2079 // remove the second HTLC when we send the HTLC back from B to A.
2080 nodes[1].node.claim_funds(payment_preimage_2);
2081 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2082 check_added_monitors!(nodes[1], 1);
2083 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2085 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2086 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2087 check_added_monitors!(nodes[0], 1);
2088 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2089 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2091 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2092 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2093 check_added_monitors!(nodes[1], 1);
2094 // B is already AwaitingRAA, so cant generate a CS here
2095 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2097 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2098 check_added_monitors!(nodes[1], 1);
2099 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2101 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2102 check_added_monitors!(nodes[0], 1);
2103 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2105 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2106 check_added_monitors!(nodes[1], 1);
2107 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2109 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2110 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2111 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2112 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2113 // on-chain as necessary).
2114 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2115 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2116 check_added_monitors!(nodes[0], 1);
2117 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2118 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2120 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2121 check_added_monitors!(nodes[1], 1);
2122 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2124 expect_pending_htlcs_forwardable!(nodes[1]);
2125 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2127 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2128 // resolve the second HTLC from A's point of view.
2129 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2130 check_added_monitors!(nodes[0], 1);
2131 expect_payment_path_successful!(nodes[0]);
2132 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2134 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2135 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2136 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2138 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2139 check_added_monitors!(nodes[1], 1);
2140 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2141 assert_eq!(events.len(), 1);
2142 SendEvent::from_event(events.remove(0))
2145 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2146 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2147 check_added_monitors!(nodes[0], 1);
2148 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2150 // Now just resolve all the outstanding messages/HTLCs for completeness...
2152 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2153 check_added_monitors!(nodes[1], 1);
2154 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2156 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2157 check_added_monitors!(nodes[1], 1);
2159 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160 check_added_monitors!(nodes[0], 1);
2161 expect_payment_path_successful!(nodes[0]);
2162 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2164 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2165 check_added_monitors!(nodes[1], 1);
2166 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2168 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2169 check_added_monitors!(nodes[0], 1);
2171 expect_pending_htlcs_forwardable!(nodes[0]);
2172 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2174 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2175 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2179 fn channel_monitor_network_test() {
2180 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2181 // tests that ChannelMonitor is able to recover from various states.
2182 let chanmon_cfgs = create_chanmon_cfgs(5);
2183 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2184 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2185 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2187 // Create some initial channels
2188 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2189 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2190 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2191 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2193 // Make sure all nodes are at the same starting height
2194 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2195 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2196 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2197 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2198 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2200 // Rebalance the network a bit by relaying one payment through all the channels...
2201 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2202 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2203 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2204 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2206 // Simple case with no pending HTLCs:
2207 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2208 check_added_monitors!(nodes[1], 1);
2209 check_closed_broadcast!(nodes[1], true);
2211 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2212 assert_eq!(node_txn.len(), 1);
2213 mine_transaction(&nodes[0], &node_txn[0]);
2214 check_added_monitors!(nodes[0], 1);
2215 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2217 check_closed_broadcast!(nodes[0], true);
2218 assert_eq!(nodes[0].node.list_channels().len(), 0);
2219 assert_eq!(nodes[1].node.list_channels().len(), 1);
2220 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2221 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2223 // One pending HTLC is discarded by the force-close:
2224 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2226 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2227 // broadcasted until we reach the timelock time).
2228 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2229 check_closed_broadcast!(nodes[1], true);
2230 check_added_monitors!(nodes[1], 1);
2232 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2233 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2234 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2235 mine_transaction(&nodes[2], &node_txn[0]);
2236 check_added_monitors!(nodes[2], 1);
2237 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2239 check_closed_broadcast!(nodes[2], true);
2240 assert_eq!(nodes[1].node.list_channels().len(), 0);
2241 assert_eq!(nodes[2].node.list_channels().len(), 1);
2242 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2243 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2245 macro_rules! claim_funds {
2246 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2248 $node.node.claim_funds($preimage);
2249 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2250 check_added_monitors!($node, 1);
2252 let events = $node.node.get_and_clear_pending_msg_events();
2253 assert_eq!(events.len(), 1);
2255 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2256 assert!(update_add_htlcs.is_empty());
2257 assert!(update_fail_htlcs.is_empty());
2258 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2260 _ => panic!("Unexpected event"),
2266 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2267 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2268 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2269 check_added_monitors!(nodes[2], 1);
2270 check_closed_broadcast!(nodes[2], true);
2271 let node2_commitment_txid;
2273 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2274 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2275 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2276 node2_commitment_txid = node_txn[0].txid();
2278 // Claim the payment on nodes[3], giving it knowledge of the preimage
2279 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2280 mine_transaction(&nodes[3], &node_txn[0]);
2281 check_added_monitors!(nodes[3], 1);
2282 check_preimage_claim(&nodes[3], &node_txn);
2284 check_closed_broadcast!(nodes[3], true);
2285 assert_eq!(nodes[2].node.list_channels().len(), 0);
2286 assert_eq!(nodes[3].node.list_channels().len(), 1);
2287 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2288 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2290 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2291 // confusing us in the following tests.
2292 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2294 // One pending HTLC to time out:
2295 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2296 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2299 let (close_chan_update_1, close_chan_update_2) = {
2300 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2301 let events = nodes[3].node.get_and_clear_pending_msg_events();
2302 assert_eq!(events.len(), 2);
2303 let close_chan_update_1 = match events[0] {
2304 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2307 _ => panic!("Unexpected event"),
2310 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2311 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2313 _ => panic!("Unexpected event"),
2315 check_added_monitors!(nodes[3], 1);
2317 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2319 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2320 node_txn.retain(|tx| {
2321 if tx.input[0].previous_output.txid == node2_commitment_txid {
2327 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2329 // Claim the payment on nodes[4], giving it knowledge of the preimage
2330 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2332 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2333 let events = nodes[4].node.get_and_clear_pending_msg_events();
2334 assert_eq!(events.len(), 2);
2335 let close_chan_update_2 = match events[0] {
2336 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2339 _ => panic!("Unexpected event"),
2342 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2343 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2345 _ => panic!("Unexpected event"),
2347 check_added_monitors!(nodes[4], 1);
2348 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2350 mine_transaction(&nodes[4], &node_txn[0]);
2351 check_preimage_claim(&nodes[4], &node_txn);
2352 (close_chan_update_1, close_chan_update_2)
2354 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2355 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2356 assert_eq!(nodes[3].node.list_channels().len(), 0);
2357 assert_eq!(nodes[4].node.list_channels().len(), 0);
2359 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2360 ChannelMonitorUpdateStatus::Completed);
2361 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2362 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2366 fn test_justice_tx() {
2367 // Test justice txn built on revoked HTLC-Success tx, against both sides
2368 let mut alice_config = UserConfig::default();
2369 alice_config.channel_handshake_config.announced_channel = true;
2370 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2371 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2372 let mut bob_config = UserConfig::default();
2373 bob_config.channel_handshake_config.announced_channel = true;
2374 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2375 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2376 let user_cfgs = [Some(alice_config), Some(bob_config)];
2377 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2378 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2379 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2382 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2383 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2384 // Create some new channels:
2385 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2387 // A pending HTLC which will be revoked:
2388 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2389 // Get the will-be-revoked local txn from nodes[0]
2390 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2391 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2392 assert_eq!(revoked_local_txn[0].input.len(), 1);
2393 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2394 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2395 assert_eq!(revoked_local_txn[1].input.len(), 1);
2396 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2397 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2398 // Revoke the old state
2399 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2402 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2404 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2405 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2406 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2408 check_spends!(node_txn[0], revoked_local_txn[0]);
2409 node_txn.swap_remove(0);
2411 check_added_monitors!(nodes[1], 1);
2412 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2413 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2415 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2416 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2417 // Verify broadcast of revoked HTLC-timeout
2418 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2419 check_added_monitors!(nodes[0], 1);
2420 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2421 // Broadcast revoked HTLC-timeout on node 1
2422 mine_transaction(&nodes[1], &node_txn[1]);
2423 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2425 get_announce_close_broadcast_events(&nodes, 0, 1);
2427 assert_eq!(nodes[0].node.list_channels().len(), 0);
2428 assert_eq!(nodes[1].node.list_channels().len(), 0);
2430 // We test justice_tx build by A on B's revoked HTLC-Success tx
2431 // Create some new channels:
2432 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2434 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2438 // A pending HTLC which will be revoked:
2439 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2440 // Get the will-be-revoked local txn from B
2441 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2442 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2443 assert_eq!(revoked_local_txn[0].input.len(), 1);
2444 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2445 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2446 // Revoke the old state
2447 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2449 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2451 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2452 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2453 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2455 check_spends!(node_txn[0], revoked_local_txn[0]);
2456 node_txn.swap_remove(0);
2458 check_added_monitors!(nodes[0], 1);
2459 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2461 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2462 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2463 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2464 check_added_monitors!(nodes[1], 1);
2465 mine_transaction(&nodes[0], &node_txn[1]);
2466 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2467 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2469 get_announce_close_broadcast_events(&nodes, 0, 1);
2470 assert_eq!(nodes[0].node.list_channels().len(), 0);
2471 assert_eq!(nodes[1].node.list_channels().len(), 0);
2475 fn revoked_output_claim() {
2476 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2477 // transaction is broadcast by its counterparty
2478 let chanmon_cfgs = create_chanmon_cfgs(2);
2479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2481 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2482 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2483 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2484 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2485 assert_eq!(revoked_local_txn.len(), 1);
2486 // Only output is the full channel value back to nodes[0]:
2487 assert_eq!(revoked_local_txn[0].output.len(), 1);
2488 // Send a payment through, updating everyone's latest commitment txn
2489 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2491 // Inform nodes[1] that nodes[0] broadcast a stale tx
2492 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2493 check_added_monitors!(nodes[1], 1);
2494 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2495 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2496 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2498 check_spends!(node_txn[0], revoked_local_txn[0]);
2500 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2501 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2502 get_announce_close_broadcast_events(&nodes, 0, 1);
2503 check_added_monitors!(nodes[0], 1);
2504 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2508 fn claim_htlc_outputs_shared_tx() {
2509 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2510 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2511 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2516 // Create some new channel:
2517 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519 // Rebalance the network to generate htlc in the two directions
2520 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2521 // 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
2522 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2523 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2525 // Get the will-be-revoked local txn from node[0]
2526 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2527 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2528 assert_eq!(revoked_local_txn[0].input.len(), 1);
2529 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2530 assert_eq!(revoked_local_txn[1].input.len(), 1);
2531 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2532 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2533 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2535 //Revoke the old state
2536 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2539 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2540 check_added_monitors!(nodes[0], 1);
2541 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2542 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2543 check_added_monitors!(nodes[1], 1);
2544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2545 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2546 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2548 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2549 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2551 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2552 check_spends!(node_txn[0], revoked_local_txn[0]);
2554 let mut witness_lens = BTreeSet::new();
2555 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2556 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2557 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2558 assert_eq!(witness_lens.len(), 3);
2559 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2560 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2561 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2563 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2564 // ANTI_REORG_DELAY confirmations.
2565 mine_transaction(&nodes[1], &node_txn[0]);
2566 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2567 expect_payment_failed!(nodes[1], payment_hash_2, false);
2569 get_announce_close_broadcast_events(&nodes, 0, 1);
2570 assert_eq!(nodes[0].node.list_channels().len(), 0);
2571 assert_eq!(nodes[1].node.list_channels().len(), 0);
2575 fn claim_htlc_outputs_single_tx() {
2576 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2577 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2578 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2583 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2585 // Rebalance the network to generate htlc in the two directions
2586 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2587 // 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
2588 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2589 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2590 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2592 // Get the will-be-revoked local txn from node[0]
2593 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2595 //Revoke the old state
2596 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2599 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2600 check_added_monitors!(nodes[0], 1);
2601 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2602 check_added_monitors!(nodes[1], 1);
2603 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2604 let mut events = nodes[0].node.get_and_clear_pending_events();
2605 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2606 match events.last().unwrap() {
2607 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2608 _ => panic!("Unexpected event"),
2611 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2612 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2614 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2615 assert_eq!(node_txn.len(), 7);
2617 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2618 assert_eq!(node_txn[0].input.len(), 1);
2619 check_spends!(node_txn[0], chan_1.3);
2620 assert_eq!(node_txn[1].input.len(), 1);
2621 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2622 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2623 check_spends!(node_txn[1], node_txn[0]);
2625 // Justice transactions are indices 2-3-4
2626 assert_eq!(node_txn[2].input.len(), 1);
2627 assert_eq!(node_txn[3].input.len(), 1);
2628 assert_eq!(node_txn[4].input.len(), 1);
2630 check_spends!(node_txn[2], revoked_local_txn[0]);
2631 check_spends!(node_txn[3], revoked_local_txn[0]);
2632 check_spends!(node_txn[4], revoked_local_txn[0]);
2634 let mut witness_lens = BTreeSet::new();
2635 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2636 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2637 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2638 assert_eq!(witness_lens.len(), 3);
2639 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2640 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2641 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2643 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2644 // ANTI_REORG_DELAY confirmations.
2645 mine_transaction(&nodes[1], &node_txn[2]);
2646 mine_transaction(&nodes[1], &node_txn[3]);
2647 mine_transaction(&nodes[1], &node_txn[4]);
2648 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2649 expect_payment_failed!(nodes[1], payment_hash_2, false);
2651 get_announce_close_broadcast_events(&nodes, 0, 1);
2652 assert_eq!(nodes[0].node.list_channels().len(), 0);
2653 assert_eq!(nodes[1].node.list_channels().len(), 0);
2657 fn test_htlc_on_chain_success() {
2658 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2659 // the preimage backward accordingly. So here we test that ChannelManager is
2660 // broadcasting the right event to other nodes in payment path.
2661 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2662 // A --------------------> B ----------------------> C (preimage)
2663 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2664 // commitment transaction was broadcast.
2665 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2667 // B should be able to claim via preimage if A then broadcasts its local tx.
2668 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2669 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2670 // PaymentSent event).
2672 let chanmon_cfgs = create_chanmon_cfgs(3);
2673 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2674 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2675 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2677 // Create some initial channels
2678 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2679 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2681 // Ensure all nodes are at the same height
2682 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2683 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2684 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2685 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2687 // Rebalance the network a bit by relaying one payment through all the channels...
2688 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2689 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2691 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2692 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2694 // Broadcast legit commitment tx from C on B's chain
2695 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2696 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2697 assert_eq!(commitment_tx.len(), 1);
2698 check_spends!(commitment_tx[0], chan_2.3);
2699 nodes[2].node.claim_funds(our_payment_preimage);
2700 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2701 nodes[2].node.claim_funds(our_payment_preimage_2);
2702 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2703 check_added_monitors!(nodes[2], 2);
2704 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2705 assert!(updates.update_add_htlcs.is_empty());
2706 assert!(updates.update_fail_htlcs.is_empty());
2707 assert!(updates.update_fail_malformed_htlcs.is_empty());
2708 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2710 mine_transaction(&nodes[2], &commitment_tx[0]);
2711 check_closed_broadcast!(nodes[2], true);
2712 check_added_monitors!(nodes[2], 1);
2713 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2714 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2715 assert_eq!(node_txn.len(), 2);
2716 check_spends!(node_txn[0], commitment_tx[0]);
2717 check_spends!(node_txn[1], commitment_tx[0]);
2718 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2719 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2720 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2721 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2722 assert_eq!(node_txn[0].lock_time.0, 0);
2723 assert_eq!(node_txn[1].lock_time.0, 0);
2725 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2726 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2727 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2728 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2730 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2731 assert_eq!(added_monitors.len(), 1);
2732 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2733 added_monitors.clear();
2735 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2736 assert_eq!(forwarded_events.len(), 3);
2737 match forwarded_events[0] {
2738 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2739 _ => panic!("Unexpected event"),
2741 let chan_id = Some(chan_1.2);
2742 match forwarded_events[1] {
2743 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2744 assert_eq!(fee_earned_msat, Some(1000));
2745 assert_eq!(prev_channel_id, chan_id);
2746 assert_eq!(claim_from_onchain_tx, true);
2747 assert_eq!(next_channel_id, Some(chan_2.2));
2748 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2752 match forwarded_events[2] {
2753 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2754 assert_eq!(fee_earned_msat, Some(1000));
2755 assert_eq!(prev_channel_id, chan_id);
2756 assert_eq!(claim_from_onchain_tx, true);
2757 assert_eq!(next_channel_id, Some(chan_2.2));
2758 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2762 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2764 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2765 assert_eq!(added_monitors.len(), 2);
2766 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2767 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2768 added_monitors.clear();
2770 assert_eq!(events.len(), 3);
2772 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2773 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2775 match nodes_2_event {
2776 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2777 _ => panic!("Unexpected event"),
2780 match nodes_0_event {
2781 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, .. } } => {
2782 assert!(update_add_htlcs.is_empty());
2783 assert!(update_fail_htlcs.is_empty());
2784 assert_eq!(update_fulfill_htlcs.len(), 1);
2785 assert!(update_fail_malformed_htlcs.is_empty());
2786 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2788 _ => panic!("Unexpected event"),
2791 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2793 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2794 _ => panic!("Unexpected event"),
2797 macro_rules! check_tx_local_broadcast {
2798 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2799 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2800 assert_eq!(node_txn.len(), 2);
2801 // Node[1]: 2 * HTLC-timeout tx
2802 // Node[0]: 2 * HTLC-timeout tx
2803 check_spends!(node_txn[0], $commitment_tx);
2804 check_spends!(node_txn[1], $commitment_tx);
2805 assert_ne!(node_txn[0].lock_time.0, 0);
2806 assert_ne!(node_txn[1].lock_time.0, 0);
2808 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2809 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2810 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2811 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2813 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2814 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2815 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2816 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2821 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2822 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2824 // Broadcast legit commitment tx from A on B's chain
2825 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2826 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2827 check_spends!(node_a_commitment_tx[0], chan_1.3);
2828 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2829 check_closed_broadcast!(nodes[1], true);
2830 check_added_monitors!(nodes[1], 1);
2831 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2832 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2833 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2834 let commitment_spend =
2835 if node_txn.len() == 1 {
2838 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2839 // FullBlockViaListen
2840 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2841 check_spends!(node_txn[1], commitment_tx[0]);
2842 check_spends!(node_txn[2], commitment_tx[0]);
2843 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2846 check_spends!(node_txn[0], commitment_tx[0]);
2847 check_spends!(node_txn[1], commitment_tx[0]);
2848 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2853 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2854 assert_eq!(commitment_spend.input.len(), 2);
2855 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2856 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2857 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2858 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2859 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2860 // we already checked the same situation with A.
2862 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2863 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2864 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2865 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2866 check_closed_broadcast!(nodes[0], true);
2867 check_added_monitors!(nodes[0], 1);
2868 let events = nodes[0].node.get_and_clear_pending_events();
2869 assert_eq!(events.len(), 5);
2870 let mut first_claimed = false;
2871 for event in events {
2873 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2874 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2875 assert!(!first_claimed);
2876 first_claimed = true;
2878 assert_eq!(payment_preimage, our_payment_preimage_2);
2879 assert_eq!(payment_hash, payment_hash_2);
2882 Event::PaymentPathSuccessful { .. } => {},
2883 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2884 _ => panic!("Unexpected event"),
2887 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2890 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2891 // Test that in case of a unilateral close onchain, we detect the state of output and
2892 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2893 // broadcasting the right event to other nodes in payment path.
2894 // A ------------------> B ----------------------> C (timeout)
2895 // B's commitment tx C's commitment tx
2897 // B's HTLC timeout tx B's timeout tx
2899 let chanmon_cfgs = create_chanmon_cfgs(3);
2900 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2901 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2902 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2903 *nodes[0].connect_style.borrow_mut() = connect_style;
2904 *nodes[1].connect_style.borrow_mut() = connect_style;
2905 *nodes[2].connect_style.borrow_mut() = connect_style;
2907 // Create some intial channels
2908 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2909 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2911 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2912 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2913 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2915 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2917 // Broadcast legit commitment tx from C on B's chain
2918 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2919 check_spends!(commitment_tx[0], chan_2.3);
2920 nodes[2].node.fail_htlc_backwards(&payment_hash);
2921 check_added_monitors!(nodes[2], 0);
2922 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2923 check_added_monitors!(nodes[2], 1);
2925 let events = nodes[2].node.get_and_clear_pending_msg_events();
2926 assert_eq!(events.len(), 1);
2928 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, .. } } => {
2929 assert!(update_add_htlcs.is_empty());
2930 assert!(!update_fail_htlcs.is_empty());
2931 assert!(update_fulfill_htlcs.is_empty());
2932 assert!(update_fail_malformed_htlcs.is_empty());
2933 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2935 _ => panic!("Unexpected event"),
2937 mine_transaction(&nodes[2], &commitment_tx[0]);
2938 check_closed_broadcast!(nodes[2], true);
2939 check_added_monitors!(nodes[2], 1);
2940 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2941 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2942 assert_eq!(node_txn.len(), 0);
2944 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2945 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2946 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2947 mine_transaction(&nodes[1], &commitment_tx[0]);
2948 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2951 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2952 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2954 check_spends!(node_txn[2], commitment_tx[0]);
2955 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2957 check_spends!(node_txn[0], chan_2.3);
2958 check_spends!(node_txn[1], node_txn[0]);
2959 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2960 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2962 timeout_tx = node_txn[2].clone();
2966 mine_transaction(&nodes[1], &timeout_tx);
2967 check_added_monitors!(nodes[1], 1);
2968 check_closed_broadcast!(nodes[1], true);
2970 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2972 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 }]);
2973 check_added_monitors!(nodes[1], 1);
2974 let events = nodes[1].node.get_and_clear_pending_msg_events();
2975 assert_eq!(events.len(), 1);
2977 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, .. } } => {
2978 assert!(update_add_htlcs.is_empty());
2979 assert!(!update_fail_htlcs.is_empty());
2980 assert!(update_fulfill_htlcs.is_empty());
2981 assert!(update_fail_malformed_htlcs.is_empty());
2982 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2984 _ => panic!("Unexpected event"),
2987 // Broadcast legit commitment tx from B on A's chain
2988 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2989 check_spends!(commitment_tx[0], chan_1.3);
2991 mine_transaction(&nodes[0], &commitment_tx[0]);
2992 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2994 check_closed_broadcast!(nodes[0], true);
2995 check_added_monitors!(nodes[0], 1);
2996 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2997 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2998 assert_eq!(node_txn.len(), 1);
2999 check_spends!(node_txn[0], commitment_tx[0]);
3000 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3004 fn test_htlc_on_chain_timeout() {
3005 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3006 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3007 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3011 fn test_simple_commitment_revoked_fail_backward() {
3012 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3013 // and fail backward accordingly.
3015 let chanmon_cfgs = create_chanmon_cfgs(3);
3016 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3017 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3018 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3020 // Create some initial channels
3021 create_announced_chan_between_nodes(&nodes, 0, 1);
3022 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3024 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3025 // Get the will-be-revoked local txn from nodes[2]
3026 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3027 // Revoke the old state
3028 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3030 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3032 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3033 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3034 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3035 check_added_monitors!(nodes[1], 1);
3036 check_closed_broadcast!(nodes[1], true);
3038 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 }]);
3039 check_added_monitors!(nodes[1], 1);
3040 let events = nodes[1].node.get_and_clear_pending_msg_events();
3041 assert_eq!(events.len(), 1);
3043 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, .. } } => {
3044 assert!(update_add_htlcs.is_empty());
3045 assert_eq!(update_fail_htlcs.len(), 1);
3046 assert!(update_fulfill_htlcs.is_empty());
3047 assert!(update_fail_malformed_htlcs.is_empty());
3048 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3050 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3051 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3052 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3054 _ => panic!("Unexpected event"),
3058 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3059 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3060 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3061 // commitment transaction anymore.
3062 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3063 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3064 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3065 // technically disallowed and we should probably handle it reasonably.
3066 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3067 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3069 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3070 // commitment_signed (implying it will be in the latest remote commitment transaction).
3071 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3072 // and once they revoke the previous commitment transaction (allowing us to send a new
3073 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3074 let chanmon_cfgs = create_chanmon_cfgs(3);
3075 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3076 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3077 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3079 // Create some initial channels
3080 create_announced_chan_between_nodes(&nodes, 0, 1);
3081 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3083 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 });
3084 // Get the will-be-revoked local txn from nodes[2]
3085 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3086 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3087 // Revoke the old state
3088 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3090 let value = if use_dust {
3091 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3092 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3093 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3094 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3097 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3098 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3099 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3101 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3102 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3103 check_added_monitors!(nodes[2], 1);
3104 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3105 assert!(updates.update_add_htlcs.is_empty());
3106 assert!(updates.update_fulfill_htlcs.is_empty());
3107 assert!(updates.update_fail_malformed_htlcs.is_empty());
3108 assert_eq!(updates.update_fail_htlcs.len(), 1);
3109 assert!(updates.update_fee.is_none());
3110 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3111 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3112 // Drop the last RAA from 3 -> 2
3114 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3115 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3116 check_added_monitors!(nodes[2], 1);
3117 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3118 assert!(updates.update_add_htlcs.is_empty());
3119 assert!(updates.update_fulfill_htlcs.is_empty());
3120 assert!(updates.update_fail_malformed_htlcs.is_empty());
3121 assert_eq!(updates.update_fail_htlcs.len(), 1);
3122 assert!(updates.update_fee.is_none());
3123 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3124 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3125 check_added_monitors!(nodes[1], 1);
3126 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3127 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3128 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3129 check_added_monitors!(nodes[2], 1);
3131 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3132 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3133 check_added_monitors!(nodes[2], 1);
3134 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3135 assert!(updates.update_add_htlcs.is_empty());
3136 assert!(updates.update_fulfill_htlcs.is_empty());
3137 assert!(updates.update_fail_malformed_htlcs.is_empty());
3138 assert_eq!(updates.update_fail_htlcs.len(), 1);
3139 assert!(updates.update_fee.is_none());
3140 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3141 // At this point first_payment_hash has dropped out of the latest two commitment
3142 // transactions that nodes[1] is tracking...
3143 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3144 check_added_monitors!(nodes[1], 1);
3145 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3146 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3147 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3148 check_added_monitors!(nodes[2], 1);
3150 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3151 // on nodes[2]'s RAA.
3152 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3153 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3154 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3155 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3156 check_added_monitors!(nodes[1], 0);
3159 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3160 // One monitor for the new revocation preimage, no second on as we won't generate a new
3161 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3162 check_added_monitors!(nodes[1], 1);
3163 let events = nodes[1].node.get_and_clear_pending_events();
3164 assert_eq!(events.len(), 2);
3166 Event::PendingHTLCsForwardable { .. } => { },
3167 _ => panic!("Unexpected event"),
3170 Event::HTLCHandlingFailed { .. } => { },
3171 _ => panic!("Unexpected event"),
3173 // Deliberately don't process the pending fail-back so they all fail back at once after
3174 // block connection just like the !deliver_bs_raa case
3177 let mut failed_htlcs = HashSet::new();
3178 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3180 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3181 check_added_monitors!(nodes[1], 1);
3182 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3184 let events = nodes[1].node.get_and_clear_pending_events();
3185 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3187 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3188 _ => panic!("Unexepected event"),
3191 Event::PaymentPathFailed { ref payment_hash, .. } => {
3192 assert_eq!(*payment_hash, fourth_payment_hash);
3194 _ => panic!("Unexpected event"),
3197 Event::PaymentFailed { ref payment_hash, .. } => {
3198 assert_eq!(*payment_hash, fourth_payment_hash);
3200 _ => panic!("Unexpected event"),
3203 nodes[1].node.process_pending_htlc_forwards();
3204 check_added_monitors!(nodes[1], 1);
3206 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3207 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3210 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3211 match nodes_2_event {
3212 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, .. } } => {
3213 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3214 assert_eq!(update_add_htlcs.len(), 1);
3215 assert!(update_fulfill_htlcs.is_empty());
3216 assert!(update_fail_htlcs.is_empty());
3217 assert!(update_fail_malformed_htlcs.is_empty());
3219 _ => panic!("Unexpected event"),
3223 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3224 match nodes_2_event {
3225 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3226 assert_eq!(channel_id, chan_2.2);
3227 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3229 _ => panic!("Unexpected event"),
3232 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3233 match nodes_0_event {
3234 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, .. } } => {
3235 assert!(update_add_htlcs.is_empty());
3236 assert_eq!(update_fail_htlcs.len(), 3);
3237 assert!(update_fulfill_htlcs.is_empty());
3238 assert!(update_fail_malformed_htlcs.is_empty());
3239 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3241 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3242 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3243 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3245 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3247 let events = nodes[0].node.get_and_clear_pending_events();
3248 assert_eq!(events.len(), 6);
3250 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3251 assert!(failed_htlcs.insert(payment_hash.0));
3252 // If we delivered B's RAA we got an unknown preimage error, not something
3253 // that we should update our routing table for.
3254 if !deliver_bs_raa {
3255 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3258 _ => panic!("Unexpected event"),
3261 Event::PaymentFailed { ref payment_hash, .. } => {
3262 assert_eq!(*payment_hash, first_payment_hash);
3264 _ => panic!("Unexpected event"),
3267 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3268 assert!(failed_htlcs.insert(payment_hash.0));
3270 _ => panic!("Unexpected event"),
3273 Event::PaymentFailed { ref payment_hash, .. } => {
3274 assert_eq!(*payment_hash, second_payment_hash);
3276 _ => panic!("Unexpected event"),
3279 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3280 assert!(failed_htlcs.insert(payment_hash.0));
3282 _ => panic!("Unexpected event"),
3285 Event::PaymentFailed { ref payment_hash, .. } => {
3286 assert_eq!(*payment_hash, third_payment_hash);
3288 _ => panic!("Unexpected event"),
3291 _ => panic!("Unexpected event"),
3294 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3296 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3297 _ => panic!("Unexpected event"),
3300 assert!(failed_htlcs.contains(&first_payment_hash.0));
3301 assert!(failed_htlcs.contains(&second_payment_hash.0));
3302 assert!(failed_htlcs.contains(&third_payment_hash.0));
3306 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3307 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3308 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3309 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3310 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3314 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3315 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3316 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3317 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3318 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3322 fn fail_backward_pending_htlc_upon_channel_failure() {
3323 let chanmon_cfgs = create_chanmon_cfgs(2);
3324 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3325 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3326 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3327 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3329 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3331 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3332 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3333 check_added_monitors!(nodes[0], 1);
3335 let payment_event = {
3336 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3337 assert_eq!(events.len(), 1);
3338 SendEvent::from_event(events.remove(0))
3340 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3341 assert_eq!(payment_event.msgs.len(), 1);
3344 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3345 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3347 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3348 check_added_monitors!(nodes[0], 0);
3350 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3353 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3355 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3357 let secp_ctx = Secp256k1::new();
3358 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3359 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3360 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3361 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3362 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3364 // Send a 0-msat update_add_htlc to fail the channel.
3365 let update_add_htlc = msgs::UpdateAddHTLC {
3371 onion_routing_packet,
3373 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3375 let events = nodes[0].node.get_and_clear_pending_events();
3376 assert_eq!(events.len(), 3);
3377 // Check that Alice fails backward the pending HTLC from the second payment.
3379 Event::PaymentPathFailed { payment_hash, .. } => {
3380 assert_eq!(payment_hash, failed_payment_hash);
3382 _ => panic!("Unexpected event"),
3385 Event::PaymentFailed { payment_hash, .. } => {
3386 assert_eq!(payment_hash, failed_payment_hash);
3388 _ => panic!("Unexpected event"),
3391 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3392 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3394 _ => panic!("Unexpected event {:?}", events[1]),
3396 check_closed_broadcast!(nodes[0], true);
3397 check_added_monitors!(nodes[0], 1);
3401 fn test_htlc_ignore_latest_remote_commitment() {
3402 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3403 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3404 let chanmon_cfgs = create_chanmon_cfgs(2);
3405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3407 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3408 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3409 // We rely on the ability to connect a block redundantly, which isn't allowed via
3410 // `chain::Listen`, so we never run the test if we randomly get assigned that
3414 create_announced_chan_between_nodes(&nodes, 0, 1);
3416 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3417 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3418 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3419 check_closed_broadcast!(nodes[0], true);
3420 check_added_monitors!(nodes[0], 1);
3421 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3423 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3424 assert_eq!(node_txn.len(), 3);
3425 assert_eq!(node_txn[0], node_txn[1]);
3427 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3428 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3429 check_closed_broadcast!(nodes[1], true);
3430 check_added_monitors!(nodes[1], 1);
3431 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3433 // Duplicate the connect_block call since this may happen due to other listeners
3434 // registering new transactions
3435 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3439 fn test_force_close_fail_back() {
3440 // Check which HTLCs are failed-backwards on channel force-closure
3441 let chanmon_cfgs = create_chanmon_cfgs(3);
3442 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3443 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3444 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3445 create_announced_chan_between_nodes(&nodes, 0, 1);
3446 create_announced_chan_between_nodes(&nodes, 1, 2);
3448 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3450 let mut payment_event = {
3451 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3452 check_added_monitors!(nodes[0], 1);
3454 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3455 assert_eq!(events.len(), 1);
3456 SendEvent::from_event(events.remove(0))
3459 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3460 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3462 expect_pending_htlcs_forwardable!(nodes[1]);
3464 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3465 assert_eq!(events_2.len(), 1);
3466 payment_event = SendEvent::from_event(events_2.remove(0));
3467 assert_eq!(payment_event.msgs.len(), 1);
3469 check_added_monitors!(nodes[1], 1);
3470 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3471 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3472 check_added_monitors!(nodes[2], 1);
3473 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3475 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3476 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3477 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3479 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3480 check_closed_broadcast!(nodes[2], true);
3481 check_added_monitors!(nodes[2], 1);
3482 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3484 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3485 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3486 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3487 // back to nodes[1] upon timeout otherwise.
3488 assert_eq!(node_txn.len(), 1);
3492 mine_transaction(&nodes[1], &tx);
3494 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3495 check_closed_broadcast!(nodes[1], true);
3496 check_added_monitors!(nodes[1], 1);
3497 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3499 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3501 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3502 .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);
3504 mine_transaction(&nodes[2], &tx);
3505 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3506 assert_eq!(node_txn.len(), 1);
3507 assert_eq!(node_txn[0].input.len(), 1);
3508 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3509 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3510 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3512 check_spends!(node_txn[0], tx);
3516 fn test_dup_events_on_peer_disconnect() {
3517 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3518 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3519 // as we used to generate the event immediately upon receipt of the payment preimage in the
3520 // update_fulfill_htlc message.
3522 let chanmon_cfgs = create_chanmon_cfgs(2);
3523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526 create_announced_chan_between_nodes(&nodes, 0, 1);
3528 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3530 nodes[1].node.claim_funds(payment_preimage);
3531 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3532 check_added_monitors!(nodes[1], 1);
3533 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3534 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3535 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3537 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3538 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3540 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3541 expect_payment_path_successful!(nodes[0]);
3545 fn test_peer_disconnected_before_funding_broadcasted() {
3546 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3547 // before the funding transaction has been broadcasted.
3548 let chanmon_cfgs = create_chanmon_cfgs(2);
3549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3551 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3553 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3554 // broadcasted, even though it's created by `nodes[0]`.
3555 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();
3556 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3557 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3558 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3559 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3561 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3562 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3564 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3566 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3567 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3569 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3570 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3573 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3576 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3577 // disconnected before the funding transaction was broadcasted.
3578 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3579 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3581 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3582 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3586 fn test_simple_peer_disconnect() {
3587 // Test that we can reconnect when there are no lost messages
3588 let chanmon_cfgs = create_chanmon_cfgs(3);
3589 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3590 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3591 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3592 create_announced_chan_between_nodes(&nodes, 0, 1);
3593 create_announced_chan_between_nodes(&nodes, 1, 2);
3595 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3596 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3597 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3599 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3600 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3601 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3602 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3604 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3605 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3606 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3608 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3609 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3610 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3611 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3613 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3614 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3616 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3617 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3619 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3621 let events = nodes[0].node.get_and_clear_pending_events();
3622 assert_eq!(events.len(), 4);
3624 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3625 assert_eq!(payment_preimage, payment_preimage_3);
3626 assert_eq!(payment_hash, payment_hash_3);
3628 _ => panic!("Unexpected event"),
3631 Event::PaymentPathSuccessful { .. } => {},
3632 _ => panic!("Unexpected event"),
3635 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3636 assert_eq!(payment_hash, payment_hash_5);
3637 assert!(payment_failed_permanently);
3639 _ => panic!("Unexpected event"),
3642 Event::PaymentFailed { payment_hash, .. } => {
3643 assert_eq!(payment_hash, payment_hash_5);
3645 _ => panic!("Unexpected event"),
3649 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3650 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3653 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3654 // Test that we can reconnect when in-flight HTLC updates get dropped
3655 let chanmon_cfgs = create_chanmon_cfgs(2);
3656 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3657 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3658 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3660 let mut as_channel_ready = None;
3661 let channel_id = if messages_delivered == 0 {
3662 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3663 as_channel_ready = Some(channel_ready);
3664 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3665 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3666 // it before the channel_reestablish message.
3669 create_announced_chan_between_nodes(&nodes, 0, 1).2
3672 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3674 let payment_event = {
3675 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3676 check_added_monitors!(nodes[0], 1);
3678 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3679 assert_eq!(events.len(), 1);
3680 SendEvent::from_event(events.remove(0))
3682 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3684 if messages_delivered < 2 {
3685 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3687 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3688 if messages_delivered >= 3 {
3689 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3690 check_added_monitors!(nodes[1], 1);
3691 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3693 if messages_delivered >= 4 {
3694 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3695 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3696 check_added_monitors!(nodes[0], 1);
3698 if messages_delivered >= 5 {
3699 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3700 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3701 // No commitment_signed so get_event_msg's assert(len == 1) passes
3702 check_added_monitors!(nodes[0], 1);
3704 if messages_delivered >= 6 {
3705 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3706 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3707 check_added_monitors!(nodes[1], 1);
3714 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3715 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3716 if messages_delivered < 3 {
3717 if simulate_broken_lnd {
3718 // lnd has a long-standing bug where they send a channel_ready prior to a
3719 // channel_reestablish if you reconnect prior to channel_ready time.
3721 // Here we simulate that behavior, delivering a channel_ready immediately on
3722 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3723 // in `reconnect_nodes` but we currently don't fail based on that.
3725 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3726 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3728 // Even if the channel_ready messages get exchanged, as long as nothing further was
3729 // received on either side, both sides will need to resend them.
3730 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3731 } else if messages_delivered == 3 {
3732 // nodes[0] still wants its RAA + commitment_signed
3733 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3734 } else if messages_delivered == 4 {
3735 // nodes[0] still wants its commitment_signed
3736 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3737 } else if messages_delivered == 5 {
3738 // nodes[1] still wants its final RAA
3739 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3740 } else if messages_delivered == 6 {
3741 // Everything was delivered...
3742 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3745 let events_1 = nodes[1].node.get_and_clear_pending_events();
3746 if messages_delivered == 0 {
3747 assert_eq!(events_1.len(), 2);
3749 Event::ChannelReady { .. } => { },
3750 _ => panic!("Unexpected event"),
3753 Event::PendingHTLCsForwardable { .. } => { },
3754 _ => panic!("Unexpected event"),
3757 assert_eq!(events_1.len(), 1);
3759 Event::PendingHTLCsForwardable { .. } => { },
3760 _ => panic!("Unexpected event"),
3764 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3765 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3766 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3768 nodes[1].node.process_pending_htlc_forwards();
3770 let events_2 = nodes[1].node.get_and_clear_pending_events();
3771 assert_eq!(events_2.len(), 1);
3773 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3774 assert_eq!(payment_hash_1, *payment_hash);
3775 assert_eq!(amount_msat, 1_000_000);
3776 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3777 assert_eq!(via_channel_id, Some(channel_id));
3779 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3780 assert!(payment_preimage.is_none());
3781 assert_eq!(payment_secret_1, *payment_secret);
3783 _ => panic!("expected PaymentPurpose::InvoicePayment")
3786 _ => panic!("Unexpected event"),
3789 nodes[1].node.claim_funds(payment_preimage_1);
3790 check_added_monitors!(nodes[1], 1);
3791 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3793 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3794 assert_eq!(events_3.len(), 1);
3795 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3796 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3797 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3798 assert!(updates.update_add_htlcs.is_empty());
3799 assert!(updates.update_fail_htlcs.is_empty());
3800 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3801 assert!(updates.update_fail_malformed_htlcs.is_empty());
3802 assert!(updates.update_fee.is_none());
3803 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3805 _ => panic!("Unexpected event"),
3808 if messages_delivered >= 1 {
3809 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3811 let events_4 = nodes[0].node.get_and_clear_pending_events();
3812 assert_eq!(events_4.len(), 1);
3814 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3815 assert_eq!(payment_preimage_1, *payment_preimage);
3816 assert_eq!(payment_hash_1, *payment_hash);
3818 _ => panic!("Unexpected event"),
3821 if messages_delivered >= 2 {
3822 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3823 check_added_monitors!(nodes[0], 1);
3824 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3826 if messages_delivered >= 3 {
3827 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3828 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3829 check_added_monitors!(nodes[1], 1);
3831 if messages_delivered >= 4 {
3832 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3833 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3834 // No commitment_signed so get_event_msg's assert(len == 1) passes
3835 check_added_monitors!(nodes[1], 1);
3837 if messages_delivered >= 5 {
3838 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3839 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3840 check_added_monitors!(nodes[0], 1);
3847 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3848 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3849 if messages_delivered < 2 {
3850 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3851 if messages_delivered < 1 {
3852 expect_payment_sent!(nodes[0], payment_preimage_1);
3854 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3856 } else if messages_delivered == 2 {
3857 // nodes[0] still wants its RAA + commitment_signed
3858 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3859 } else if messages_delivered == 3 {
3860 // nodes[0] still wants its commitment_signed
3861 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3862 } else if messages_delivered == 4 {
3863 // nodes[1] still wants its final RAA
3864 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3865 } else if messages_delivered == 5 {
3866 // Everything was delivered...
3867 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3870 if messages_delivered == 1 || messages_delivered == 2 {
3871 expect_payment_path_successful!(nodes[0]);
3873 if messages_delivered <= 5 {
3874 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3875 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3877 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3879 if messages_delivered > 2 {
3880 expect_payment_path_successful!(nodes[0]);
3883 // Channel should still work fine...
3884 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3885 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3886 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3890 fn test_drop_messages_peer_disconnect_a() {
3891 do_test_drop_messages_peer_disconnect(0, true);
3892 do_test_drop_messages_peer_disconnect(0, false);
3893 do_test_drop_messages_peer_disconnect(1, false);
3894 do_test_drop_messages_peer_disconnect(2, false);
3898 fn test_drop_messages_peer_disconnect_b() {
3899 do_test_drop_messages_peer_disconnect(3, false);
3900 do_test_drop_messages_peer_disconnect(4, false);
3901 do_test_drop_messages_peer_disconnect(5, false);
3902 do_test_drop_messages_peer_disconnect(6, false);
3906 fn test_channel_ready_without_best_block_updated() {
3907 // Previously, if we were offline when a funding transaction was locked in, and then we came
3908 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3909 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3910 // channel_ready immediately instead.
3911 let chanmon_cfgs = create_chanmon_cfgs(2);
3912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3914 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3915 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3917 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3919 let conf_height = nodes[0].best_block_info().1 + 1;
3920 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3921 let block_txn = [funding_tx];
3922 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3923 let conf_block_header = nodes[0].get_block_header(conf_height);
3924 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3926 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3927 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3928 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3932 fn test_drop_messages_peer_disconnect_dual_htlc() {
3933 // Test that we can handle reconnecting when both sides of a channel have pending
3934 // commitment_updates when we disconnect.
3935 let chanmon_cfgs = create_chanmon_cfgs(2);
3936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3938 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3939 create_announced_chan_between_nodes(&nodes, 0, 1);
3941 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3943 // Now try to send a second payment which will fail to send
3944 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3945 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3946 check_added_monitors!(nodes[0], 1);
3948 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3949 assert_eq!(events_1.len(), 1);
3951 MessageSendEvent::UpdateHTLCs { .. } => {},
3952 _ => panic!("Unexpected event"),
3955 nodes[1].node.claim_funds(payment_preimage_1);
3956 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3957 check_added_monitors!(nodes[1], 1);
3959 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3960 assert_eq!(events_2.len(), 1);
3962 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 } } => {
3963 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3964 assert!(update_add_htlcs.is_empty());
3965 assert_eq!(update_fulfill_htlcs.len(), 1);
3966 assert!(update_fail_htlcs.is_empty());
3967 assert!(update_fail_malformed_htlcs.is_empty());
3968 assert!(update_fee.is_none());
3970 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3971 let events_3 = nodes[0].node.get_and_clear_pending_events();
3972 assert_eq!(events_3.len(), 1);
3974 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3975 assert_eq!(*payment_preimage, payment_preimage_1);
3976 assert_eq!(*payment_hash, payment_hash_1);
3978 _ => panic!("Unexpected event"),
3981 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3982 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3983 // No commitment_signed so get_event_msg's assert(len == 1) passes
3984 check_added_monitors!(nodes[0], 1);
3986 _ => panic!("Unexpected event"),
3989 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3990 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3992 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();
3993 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3994 assert_eq!(reestablish_1.len(), 1);
3995 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();
3996 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3997 assert_eq!(reestablish_2.len(), 1);
3999 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4000 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4001 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4002 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4004 assert!(as_resp.0.is_none());
4005 assert!(bs_resp.0.is_none());
4007 assert!(bs_resp.1.is_none());
4008 assert!(bs_resp.2.is_none());
4010 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4012 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4013 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4014 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4015 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4016 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4017 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4018 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4019 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4020 // No commitment_signed so get_event_msg's assert(len == 1) passes
4021 check_added_monitors!(nodes[1], 1);
4023 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4024 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4025 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4026 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4027 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4028 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4029 assert!(bs_second_commitment_signed.update_fee.is_none());
4030 check_added_monitors!(nodes[1], 1);
4032 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4033 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4034 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4035 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4036 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4037 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4038 assert!(as_commitment_signed.update_fee.is_none());
4039 check_added_monitors!(nodes[0], 1);
4041 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4042 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4043 // No commitment_signed so get_event_msg's assert(len == 1) passes
4044 check_added_monitors!(nodes[0], 1);
4046 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4047 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4048 // No commitment_signed so get_event_msg's assert(len == 1) passes
4049 check_added_monitors!(nodes[1], 1);
4051 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4052 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4053 check_added_monitors!(nodes[1], 1);
4055 expect_pending_htlcs_forwardable!(nodes[1]);
4057 let events_5 = nodes[1].node.get_and_clear_pending_events();
4058 assert_eq!(events_5.len(), 1);
4060 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4061 assert_eq!(payment_hash_2, *payment_hash);
4063 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4064 assert!(payment_preimage.is_none());
4065 assert_eq!(payment_secret_2, *payment_secret);
4067 _ => panic!("expected PaymentPurpose::InvoicePayment")
4070 _ => panic!("Unexpected event"),
4073 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4074 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4075 check_added_monitors!(nodes[0], 1);
4077 expect_payment_path_successful!(nodes[0]);
4078 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4081 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4082 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4083 // to avoid our counterparty failing the channel.
4084 let chanmon_cfgs = create_chanmon_cfgs(2);
4085 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4086 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4087 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4089 create_announced_chan_between_nodes(&nodes, 0, 1);
4091 let our_payment_hash = if send_partial_mpp {
4092 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4093 // Use the utility function send_payment_along_path to send the payment with MPP data which
4094 // indicates there are more HTLCs coming.
4095 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.
4096 let payment_id = PaymentId([42; 32]);
4097 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4098 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
4099 check_added_monitors!(nodes[0], 1);
4100 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4101 assert_eq!(events.len(), 1);
4102 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4103 // hop should *not* yet generate any PaymentClaimable event(s).
4104 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4107 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4110 let mut block = Block {
4111 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4114 connect_block(&nodes[0], &block);
4115 connect_block(&nodes[1], &block);
4116 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4117 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4118 block.header.prev_blockhash = block.block_hash();
4119 connect_block(&nodes[0], &block);
4120 connect_block(&nodes[1], &block);
4123 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4125 check_added_monitors!(nodes[1], 1);
4126 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4127 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4128 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4129 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4130 assert!(htlc_timeout_updates.update_fee.is_none());
4132 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4133 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4134 // 100_000 msat as u64, followed by the height at which we failed back above
4135 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4136 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4137 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4141 fn test_htlc_timeout() {
4142 do_test_htlc_timeout(true);
4143 do_test_htlc_timeout(false);
4146 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4147 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4148 let chanmon_cfgs = create_chanmon_cfgs(3);
4149 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4150 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4151 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4152 create_announced_chan_between_nodes(&nodes, 0, 1);
4153 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4155 // Make sure all nodes are at the same starting height
4156 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4157 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4158 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4160 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4161 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4163 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4165 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4166 check_added_monitors!(nodes[1], 1);
4168 // Now attempt to route a second payment, which should be placed in the holding cell
4169 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4170 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4171 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4173 check_added_monitors!(nodes[0], 1);
4174 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4175 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4176 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4177 expect_pending_htlcs_forwardable!(nodes[1]);
4179 check_added_monitors!(nodes[1], 0);
4181 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4182 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4183 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4184 connect_blocks(&nodes[1], 1);
4187 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 }]);
4188 check_added_monitors!(nodes[1], 1);
4189 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4190 assert_eq!(fail_commit.len(), 1);
4191 match fail_commit[0] {
4192 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4193 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4194 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4196 _ => unreachable!(),
4198 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4200 expect_payment_failed!(nodes[1], second_payment_hash, false);
4205 fn test_holding_cell_htlc_add_timeouts() {
4206 do_test_holding_cell_htlc_add_timeouts(false);
4207 do_test_holding_cell_htlc_add_timeouts(true);
4210 macro_rules! check_spendable_outputs {
4211 ($node: expr, $keysinterface: expr) => {
4213 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4214 let mut txn = Vec::new();
4215 let mut all_outputs = Vec::new();
4216 let secp_ctx = Secp256k1::new();
4217 for event in events.drain(..) {
4219 Event::SpendableOutputs { mut outputs } => {
4220 for outp in outputs.drain(..) {
4221 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4222 all_outputs.push(outp);
4225 _ => panic!("Unexpected event"),
4228 if all_outputs.len() > 1 {
4229 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, &secp_ctx) {
4239 fn test_claim_sizeable_push_msat() {
4240 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4241 let chanmon_cfgs = create_chanmon_cfgs(2);
4242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4244 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4246 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4247 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4248 check_closed_broadcast!(nodes[1], true);
4249 check_added_monitors!(nodes[1], 1);
4250 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4251 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4252 assert_eq!(node_txn.len(), 1);
4253 check_spends!(node_txn[0], chan.3);
4254 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
4256 mine_transaction(&nodes[1], &node_txn[0]);
4257 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4259 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4260 assert_eq!(spend_txn.len(), 1);
4261 assert_eq!(spend_txn[0].input.len(), 1);
4262 check_spends!(spend_txn[0], node_txn[0]);
4263 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4267 fn test_claim_on_remote_sizeable_push_msat() {
4268 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4269 // to_remote output is encumbered by a P2WPKH
4270 let chanmon_cfgs = create_chanmon_cfgs(2);
4271 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4272 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4273 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4275 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4276 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4277 check_closed_broadcast!(nodes[0], true);
4278 check_added_monitors!(nodes[0], 1);
4279 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4281 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4282 assert_eq!(node_txn.len(), 1);
4283 check_spends!(node_txn[0], chan.3);
4284 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
4286 mine_transaction(&nodes[1], &node_txn[0]);
4287 check_closed_broadcast!(nodes[1], true);
4288 check_added_monitors!(nodes[1], 1);
4289 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4290 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4292 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4293 assert_eq!(spend_txn.len(), 1);
4294 check_spends!(spend_txn[0], node_txn[0]);
4298 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4299 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4300 // to_remote output is encumbered by a P2WPKH
4302 let chanmon_cfgs = create_chanmon_cfgs(2);
4303 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4304 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4305 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4307 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4308 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4309 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4310 assert_eq!(revoked_local_txn[0].input.len(), 1);
4311 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4313 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4314 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4315 check_closed_broadcast!(nodes[1], true);
4316 check_added_monitors!(nodes[1], 1);
4317 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4319 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4320 mine_transaction(&nodes[1], &node_txn[0]);
4321 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4323 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4324 assert_eq!(spend_txn.len(), 3);
4325 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4326 check_spends!(spend_txn[1], node_txn[0]);
4327 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4331 fn test_static_spendable_outputs_preimage_tx() {
4332 let chanmon_cfgs = create_chanmon_cfgs(2);
4333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4335 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4337 // Create some initial channels
4338 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4340 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4342 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4343 assert_eq!(commitment_tx[0].input.len(), 1);
4344 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4346 // Settle A's commitment tx on B's chain
4347 nodes[1].node.claim_funds(payment_preimage);
4348 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4349 check_added_monitors!(nodes[1], 1);
4350 mine_transaction(&nodes[1], &commitment_tx[0]);
4351 check_added_monitors!(nodes[1], 1);
4352 let events = nodes[1].node.get_and_clear_pending_msg_events();
4354 MessageSendEvent::UpdateHTLCs { .. } => {},
4355 _ => panic!("Unexpected event"),
4358 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4359 _ => panic!("Unexepected event"),
4362 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4363 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4364 assert_eq!(node_txn.len(), 1);
4365 check_spends!(node_txn[0], commitment_tx[0]);
4366 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4368 mine_transaction(&nodes[1], &node_txn[0]);
4369 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4370 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4372 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4373 assert_eq!(spend_txn.len(), 1);
4374 check_spends!(spend_txn[0], node_txn[0]);
4378 fn test_static_spendable_outputs_timeout_tx() {
4379 let chanmon_cfgs = create_chanmon_cfgs(2);
4380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4382 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4384 // Create some initial channels
4385 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4387 // Rebalance the network a bit by relaying one payment through all the channels ...
4388 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4390 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4392 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4393 assert_eq!(commitment_tx[0].input.len(), 1);
4394 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4396 // Settle A's commitment tx on B' chain
4397 mine_transaction(&nodes[1], &commitment_tx[0]);
4398 check_added_monitors!(nodes[1], 1);
4399 let events = nodes[1].node.get_and_clear_pending_msg_events();
4401 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4402 _ => panic!("Unexpected event"),
4404 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4406 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4407 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4408 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4409 check_spends!(node_txn[0], commitment_tx[0].clone());
4410 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4412 mine_transaction(&nodes[1], &node_txn[0]);
4413 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4414 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4415 expect_payment_failed!(nodes[1], our_payment_hash, false);
4417 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4418 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4419 check_spends!(spend_txn[0], commitment_tx[0]);
4420 check_spends!(spend_txn[1], node_txn[0]);
4421 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4425 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4426 let chanmon_cfgs = create_chanmon_cfgs(2);
4427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4431 // Create some initial channels
4432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4434 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4435 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4436 assert_eq!(revoked_local_txn[0].input.len(), 1);
4437 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4439 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4441 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4442 check_closed_broadcast!(nodes[1], true);
4443 check_added_monitors!(nodes[1], 1);
4444 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4446 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4447 assert_eq!(node_txn.len(), 1);
4448 assert_eq!(node_txn[0].input.len(), 2);
4449 check_spends!(node_txn[0], revoked_local_txn[0]);
4451 mine_transaction(&nodes[1], &node_txn[0]);
4452 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4454 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4455 assert_eq!(spend_txn.len(), 1);
4456 check_spends!(spend_txn[0], node_txn[0]);
4460 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4461 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4462 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
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 // A will generate HTLC-Timeout from revoked commitment tx
4478 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4479 check_closed_broadcast!(nodes[0], true);
4480 check_added_monitors!(nodes[0], 1);
4481 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4482 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4484 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4485 assert_eq!(revoked_htlc_txn.len(), 1);
4486 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4487 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4488 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4489 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4491 // B will generate justice tx from A's revoked commitment/HTLC tx
4492 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4493 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4494 check_closed_broadcast!(nodes[1], true);
4495 check_added_monitors!(nodes[1], 1);
4496 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4498 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4499 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4500 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4501 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4502 // transactions next...
4503 assert_eq!(node_txn[0].input.len(), 3);
4504 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4506 assert_eq!(node_txn[1].input.len(), 2);
4507 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4508 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4509 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4511 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4512 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4515 mine_transaction(&nodes[1], &node_txn[1]);
4516 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4518 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4519 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4520 assert_eq!(spend_txn.len(), 1);
4521 assert_eq!(spend_txn[0].input.len(), 1);
4522 check_spends!(spend_txn[0], node_txn[1]);
4526 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4527 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4528 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4531 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4533 // Create some initial channels
4534 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4536 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4537 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4538 assert_eq!(revoked_local_txn[0].input.len(), 1);
4539 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4541 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4542 assert_eq!(revoked_local_txn[0].output.len(), 2);
4544 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4546 // B will generate HTLC-Success from revoked commitment tx
4547 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4548 check_closed_broadcast!(nodes[1], true);
4549 check_added_monitors!(nodes[1], 1);
4550 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4551 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4553 assert_eq!(revoked_htlc_txn.len(), 1);
4554 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4555 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4556 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4558 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4559 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4560 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4562 // A will generate justice tx from B's revoked commitment/HTLC tx
4563 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4564 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4565 check_closed_broadcast!(nodes[0], true);
4566 check_added_monitors!(nodes[0], 1);
4567 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4569 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4570 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4572 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4573 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4574 // transactions next...
4575 assert_eq!(node_txn[0].input.len(), 2);
4576 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4577 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4578 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4580 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4581 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4584 assert_eq!(node_txn[1].input.len(), 1);
4585 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4587 mine_transaction(&nodes[0], &node_txn[1]);
4588 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4590 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4591 // didn't try to generate any new transactions.
4593 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4594 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4595 assert_eq!(spend_txn.len(), 3);
4596 assert_eq!(spend_txn[0].input.len(), 1);
4597 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4598 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4599 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4600 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4604 fn test_onchain_to_onchain_claim() {
4605 // Test that in case of channel closure, we detect the state of output and claim HTLC
4606 // on downstream peer's remote commitment tx.
4607 // First, have C claim an HTLC against its own latest commitment transaction.
4608 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4610 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4613 let chanmon_cfgs = create_chanmon_cfgs(3);
4614 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4615 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4616 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4618 // Create some initial channels
4619 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4620 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4622 // Ensure all nodes are at the same height
4623 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4624 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4625 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4626 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4628 // Rebalance the network a bit by relaying one payment through all the channels ...
4629 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4630 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4632 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4633 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4634 check_spends!(commitment_tx[0], chan_2.3);
4635 nodes[2].node.claim_funds(payment_preimage);
4636 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4637 check_added_monitors!(nodes[2], 1);
4638 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4639 assert!(updates.update_add_htlcs.is_empty());
4640 assert!(updates.update_fail_htlcs.is_empty());
4641 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4642 assert!(updates.update_fail_malformed_htlcs.is_empty());
4644 mine_transaction(&nodes[2], &commitment_tx[0]);
4645 check_closed_broadcast!(nodes[2], true);
4646 check_added_monitors!(nodes[2], 1);
4647 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4649 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4650 assert_eq!(c_txn.len(), 1);
4651 check_spends!(c_txn[0], commitment_tx[0]);
4652 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4653 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4654 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4656 // 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
4657 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4658 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4659 check_added_monitors!(nodes[1], 1);
4660 let events = nodes[1].node.get_and_clear_pending_events();
4661 assert_eq!(events.len(), 2);
4663 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4664 _ => panic!("Unexpected event"),
4667 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4668 assert_eq!(fee_earned_msat, Some(1000));
4669 assert_eq!(prev_channel_id, Some(chan_1.2));
4670 assert_eq!(claim_from_onchain_tx, true);
4671 assert_eq!(next_channel_id, Some(chan_2.2));
4672 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4674 _ => panic!("Unexpected event"),
4676 check_added_monitors!(nodes[1], 1);
4677 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4678 assert_eq!(msg_events.len(), 3);
4679 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4680 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4682 match nodes_2_event {
4683 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4684 _ => panic!("Unexpected event"),
4687 match nodes_0_event {
4688 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, .. } } => {
4689 assert!(update_add_htlcs.is_empty());
4690 assert!(update_fail_htlcs.is_empty());
4691 assert_eq!(update_fulfill_htlcs.len(), 1);
4692 assert!(update_fail_malformed_htlcs.is_empty());
4693 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4695 _ => panic!("Unexpected event"),
4698 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4699 match msg_events[0] {
4700 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4701 _ => panic!("Unexpected event"),
4704 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4705 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4706 mine_transaction(&nodes[1], &commitment_tx[0]);
4707 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4708 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4709 // ChannelMonitor: HTLC-Success tx
4710 assert_eq!(b_txn.len(), 1);
4711 check_spends!(b_txn[0], commitment_tx[0]);
4712 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4713 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4714 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4716 check_closed_broadcast!(nodes[1], true);
4717 check_added_monitors!(nodes[1], 1);
4721 fn test_duplicate_payment_hash_one_failure_one_success() {
4722 // Topology : A --> B --> C --> D
4723 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4724 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4725 // we forward one of the payments onwards to D.
4726 let chanmon_cfgs = create_chanmon_cfgs(4);
4727 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4728 // When this test was written, the default base fee floated based on the HTLC count.
4729 // It is now fixed, so we simply set the fee to the expected value here.
4730 let mut config = test_default_channel_config();
4731 config.channel_config.forwarding_fee_base_msat = 196;
4732 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4733 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4734 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4736 create_announced_chan_between_nodes(&nodes, 0, 1);
4737 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4738 create_announced_chan_between_nodes(&nodes, 2, 3);
4740 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4741 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4742 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4743 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4744 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4746 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4748 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4749 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4750 // script push size limit so that the below script length checks match
4751 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4752 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4753 .with_features(nodes[3].node.invoice_features());
4754 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4755 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4757 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4758 assert_eq!(commitment_txn[0].input.len(), 1);
4759 check_spends!(commitment_txn[0], chan_2.3);
4761 mine_transaction(&nodes[1], &commitment_txn[0]);
4762 check_closed_broadcast!(nodes[1], true);
4763 check_added_monitors!(nodes[1], 1);
4764 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4765 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4767 let htlc_timeout_tx;
4768 { // Extract one of the two HTLC-Timeout transaction
4769 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4770 // ChannelMonitor: timeout tx * 2-or-3
4771 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4773 check_spends!(node_txn[0], commitment_txn[0]);
4774 assert_eq!(node_txn[0].input.len(), 1);
4775 assert_eq!(node_txn[0].output.len(), 1);
4777 if node_txn.len() > 2 {
4778 check_spends!(node_txn[1], commitment_txn[0]);
4779 assert_eq!(node_txn[1].input.len(), 1);
4780 assert_eq!(node_txn[1].output.len(), 1);
4781 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4783 check_spends!(node_txn[2], commitment_txn[0]);
4784 assert_eq!(node_txn[2].input.len(), 1);
4785 assert_eq!(node_txn[2].output.len(), 1);
4786 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4788 check_spends!(node_txn[1], commitment_txn[0]);
4789 assert_eq!(node_txn[1].input.len(), 1);
4790 assert_eq!(node_txn[1].output.len(), 1);
4791 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4794 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4795 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4796 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4797 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4798 if node_txn.len() > 2 {
4799 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4800 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4802 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4806 nodes[2].node.claim_funds(our_payment_preimage);
4807 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4809 mine_transaction(&nodes[2], &commitment_txn[0]);
4810 check_added_monitors!(nodes[2], 2);
4811 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4812 let events = nodes[2].node.get_and_clear_pending_msg_events();
4814 MessageSendEvent::UpdateHTLCs { .. } => {},
4815 _ => panic!("Unexpected event"),
4818 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4819 _ => panic!("Unexepected event"),
4821 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4822 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4823 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4824 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4825 assert_eq!(htlc_success_txn[0].input.len(), 1);
4826 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4827 assert_eq!(htlc_success_txn[1].input.len(), 1);
4828 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4829 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4830 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4832 mine_transaction(&nodes[1], &htlc_timeout_tx);
4833 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4834 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 }]);
4835 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4836 assert!(htlc_updates.update_add_htlcs.is_empty());
4837 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4838 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4839 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4840 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4841 check_added_monitors!(nodes[1], 1);
4843 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4844 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4846 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4848 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4850 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4851 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4852 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4853 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4854 assert!(updates.update_add_htlcs.is_empty());
4855 assert!(updates.update_fail_htlcs.is_empty());
4856 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4857 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4858 assert!(updates.update_fail_malformed_htlcs.is_empty());
4859 check_added_monitors!(nodes[1], 1);
4861 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4862 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4864 let events = nodes[0].node.get_and_clear_pending_events();
4866 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4867 assert_eq!(*payment_preimage, our_payment_preimage);
4868 assert_eq!(*payment_hash, duplicate_payment_hash);
4870 _ => panic!("Unexpected event"),
4875 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4876 let chanmon_cfgs = create_chanmon_cfgs(2);
4877 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4878 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4879 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4881 // Create some initial channels
4882 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4884 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4885 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4886 assert_eq!(local_txn.len(), 1);
4887 assert_eq!(local_txn[0].input.len(), 1);
4888 check_spends!(local_txn[0], chan_1.3);
4890 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4891 nodes[1].node.claim_funds(payment_preimage);
4892 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4893 check_added_monitors!(nodes[1], 1);
4895 mine_transaction(&nodes[1], &local_txn[0]);
4896 check_added_monitors!(nodes[1], 1);
4897 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4898 let events = nodes[1].node.get_and_clear_pending_msg_events();
4900 MessageSendEvent::UpdateHTLCs { .. } => {},
4901 _ => panic!("Unexpected event"),
4904 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4905 _ => panic!("Unexepected event"),
4908 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4909 assert_eq!(node_txn.len(), 1);
4910 assert_eq!(node_txn[0].input.len(), 1);
4911 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4912 check_spends!(node_txn[0], local_txn[0]);
4916 mine_transaction(&nodes[1], &node_tx);
4917 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4919 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4920 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4921 assert_eq!(spend_txn.len(), 1);
4922 assert_eq!(spend_txn[0].input.len(), 1);
4923 check_spends!(spend_txn[0], node_tx);
4924 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4927 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4928 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4929 // unrevoked commitment transaction.
4930 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4931 // a remote RAA before they could be failed backwards (and combinations thereof).
4932 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4933 // use the same payment hashes.
4934 // Thus, we use a six-node network:
4939 // And test where C fails back to A/B when D announces its latest commitment transaction
4940 let chanmon_cfgs = create_chanmon_cfgs(6);
4941 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4942 // When this test was written, the default base fee floated based on the HTLC count.
4943 // It is now fixed, so we simply set the fee to the expected value here.
4944 let mut config = test_default_channel_config();
4945 config.channel_config.forwarding_fee_base_msat = 196;
4946 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4947 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4948 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4950 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4951 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4952 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4953 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4954 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4956 // Rebalance and check output sanity...
4957 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4958 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4959 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4961 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4962 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4964 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
4966 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
4967 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4969 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
4971 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
4973 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4975 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4976 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4978 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());
4980 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());
4983 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4985 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4986 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
4989 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
4991 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4992 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());
4994 // Double-check that six of the new HTLC were added
4995 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4996 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4997 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4998 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5000 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5001 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5002 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5003 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5004 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5005 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5006 check_added_monitors!(nodes[4], 0);
5008 let failed_destinations = vec![
5009 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5010 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5011 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5012 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5014 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5015 check_added_monitors!(nodes[4], 1);
5017 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5018 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5019 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5020 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5021 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5022 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5024 // Fail 3rd below-dust and 7th above-dust HTLCs
5025 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5026 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5027 check_added_monitors!(nodes[5], 0);
5029 let failed_destinations_2 = vec![
5030 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5031 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5033 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5034 check_added_monitors!(nodes[5], 1);
5036 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5037 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5038 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5039 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5041 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5043 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5044 let failed_destinations_3 = vec![
5045 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5046 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5047 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5048 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5049 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5050 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5052 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5053 check_added_monitors!(nodes[3], 1);
5054 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5055 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5056 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5057 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5058 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5059 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5060 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5061 if deliver_last_raa {
5062 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5064 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5067 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5068 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5069 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5070 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5072 // We now broadcast the latest commitment transaction, which *should* result in failures for
5073 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5074 // the non-broadcast above-dust HTLCs.
5076 // Alternatively, we may broadcast the previous commitment transaction, which should only
5077 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5078 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5080 if announce_latest {
5081 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5083 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5085 let events = nodes[2].node.get_and_clear_pending_events();
5086 let close_event = if deliver_last_raa {
5087 assert_eq!(events.len(), 2 + 6);
5088 events.last().clone().unwrap()
5090 assert_eq!(events.len(), 1);
5091 events.last().clone().unwrap()
5094 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5095 _ => panic!("Unexpected event"),
5098 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5099 check_closed_broadcast!(nodes[2], true);
5100 if deliver_last_raa {
5101 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5103 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();
5104 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5106 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5107 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5109 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5112 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5114 check_added_monitors!(nodes[2], 3);
5116 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5117 assert_eq!(cs_msgs.len(), 2);
5118 let mut a_done = false;
5119 for msg in cs_msgs {
5121 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5122 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5123 // should be failed-backwards here.
5124 let target = if *node_id == nodes[0].node.get_our_node_id() {
5125 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5126 for htlc in &updates.update_fail_htlcs {
5127 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 });
5129 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5134 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5135 for htlc in &updates.update_fail_htlcs {
5136 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5138 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5139 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5142 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5143 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5144 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5145 if announce_latest {
5146 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5147 if *node_id == nodes[0].node.get_our_node_id() {
5148 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5151 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5153 _ => panic!("Unexpected event"),
5157 let as_events = nodes[0].node.get_and_clear_pending_events();
5158 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5159 let mut as_failds = HashSet::new();
5160 let mut as_updates = 0;
5161 for event in as_events.iter() {
5162 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5163 assert!(as_failds.insert(*payment_hash));
5164 if *payment_hash != payment_hash_2 {
5165 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5167 assert!(!payment_failed_permanently);
5169 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5172 } else if let &Event::PaymentFailed { .. } = event {
5173 } else { panic!("Unexpected event"); }
5175 assert!(as_failds.contains(&payment_hash_1));
5176 assert!(as_failds.contains(&payment_hash_2));
5177 if announce_latest {
5178 assert!(as_failds.contains(&payment_hash_3));
5179 assert!(as_failds.contains(&payment_hash_5));
5181 assert!(as_failds.contains(&payment_hash_6));
5183 let bs_events = nodes[1].node.get_and_clear_pending_events();
5184 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5185 let mut bs_failds = HashSet::new();
5186 let mut bs_updates = 0;
5187 for event in bs_events.iter() {
5188 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5189 assert!(bs_failds.insert(*payment_hash));
5190 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5191 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5193 assert!(!payment_failed_permanently);
5195 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5198 } else if let &Event::PaymentFailed { .. } = event {
5199 } else { panic!("Unexpected event"); }
5201 assert!(bs_failds.contains(&payment_hash_1));
5202 assert!(bs_failds.contains(&payment_hash_2));
5203 if announce_latest {
5204 assert!(bs_failds.contains(&payment_hash_4));
5206 assert!(bs_failds.contains(&payment_hash_5));
5208 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5209 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5210 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5211 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5212 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5213 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5217 fn test_fail_backwards_latest_remote_announce_a() {
5218 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5222 fn test_fail_backwards_latest_remote_announce_b() {
5223 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5227 fn test_fail_backwards_previous_remote_announce() {
5228 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5229 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5230 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5234 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5235 let chanmon_cfgs = create_chanmon_cfgs(2);
5236 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5237 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5238 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5240 // Create some initial channels
5241 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5243 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5244 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5245 assert_eq!(local_txn[0].input.len(), 1);
5246 check_spends!(local_txn[0], chan_1.3);
5248 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5249 mine_transaction(&nodes[0], &local_txn[0]);
5250 check_closed_broadcast!(nodes[0], true);
5251 check_added_monitors!(nodes[0], 1);
5252 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5253 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5255 let htlc_timeout = {
5256 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5257 assert_eq!(node_txn.len(), 1);
5258 assert_eq!(node_txn[0].input.len(), 1);
5259 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5260 check_spends!(node_txn[0], local_txn[0]);
5264 mine_transaction(&nodes[0], &htlc_timeout);
5265 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5266 expect_payment_failed!(nodes[0], our_payment_hash, false);
5268 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5269 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5270 assert_eq!(spend_txn.len(), 3);
5271 check_spends!(spend_txn[0], local_txn[0]);
5272 assert_eq!(spend_txn[1].input.len(), 1);
5273 check_spends!(spend_txn[1], htlc_timeout);
5274 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5275 assert_eq!(spend_txn[2].input.len(), 2);
5276 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5277 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5278 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5282 fn test_key_derivation_params() {
5283 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5284 // manager rotation to test that `channel_keys_id` returned in
5285 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5286 // then derive a `delayed_payment_key`.
5288 let chanmon_cfgs = create_chanmon_cfgs(3);
5290 // We manually create the node configuration to backup the seed.
5291 let seed = [42; 32];
5292 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5293 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);
5294 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5295 let scorer = Mutex::new(test_utils::TestScorer::new());
5296 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5297 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)) };
5298 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5299 node_cfgs.remove(0);
5300 node_cfgs.insert(0, node);
5302 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5303 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5305 // Create some initial channels
5306 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5308 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5309 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5310 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5312 // Ensure all nodes are at the same height
5313 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5314 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5315 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5316 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5318 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5319 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5320 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5321 assert_eq!(local_txn_1[0].input.len(), 1);
5322 check_spends!(local_txn_1[0], chan_1.3);
5324 // We check funding pubkey are unique
5325 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]));
5326 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]));
5327 if from_0_funding_key_0 == from_1_funding_key_0
5328 || from_0_funding_key_0 == from_1_funding_key_1
5329 || from_0_funding_key_1 == from_1_funding_key_0
5330 || from_0_funding_key_1 == from_1_funding_key_1 {
5331 panic!("Funding pubkeys aren't unique");
5334 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5335 mine_transaction(&nodes[0], &local_txn_1[0]);
5336 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5337 check_closed_broadcast!(nodes[0], true);
5338 check_added_monitors!(nodes[0], 1);
5339 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5341 let htlc_timeout = {
5342 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5343 assert_eq!(node_txn.len(), 1);
5344 assert_eq!(node_txn[0].input.len(), 1);
5345 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5346 check_spends!(node_txn[0], local_txn_1[0]);
5350 mine_transaction(&nodes[0], &htlc_timeout);
5351 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5352 expect_payment_failed!(nodes[0], our_payment_hash, false);
5354 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5355 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5356 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5357 assert_eq!(spend_txn.len(), 3);
5358 check_spends!(spend_txn[0], local_txn_1[0]);
5359 assert_eq!(spend_txn[1].input.len(), 1);
5360 check_spends!(spend_txn[1], htlc_timeout);
5361 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5362 assert_eq!(spend_txn[2].input.len(), 2);
5363 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5364 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5365 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5369 fn test_static_output_closing_tx() {
5370 let chanmon_cfgs = create_chanmon_cfgs(2);
5371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5373 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5375 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5377 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5378 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5380 mine_transaction(&nodes[0], &closing_tx);
5381 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5382 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5384 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5385 assert_eq!(spend_txn.len(), 1);
5386 check_spends!(spend_txn[0], closing_tx);
5388 mine_transaction(&nodes[1], &closing_tx);
5389 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5390 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5392 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5393 assert_eq!(spend_txn.len(), 1);
5394 check_spends!(spend_txn[0], closing_tx);
5397 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5398 let chanmon_cfgs = create_chanmon_cfgs(2);
5399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5401 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5402 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5404 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5406 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5407 // present in B's local commitment transaction, but none of A's commitment transactions.
5408 nodes[1].node.claim_funds(payment_preimage);
5409 check_added_monitors!(nodes[1], 1);
5410 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5412 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5413 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5414 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5416 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5417 check_added_monitors!(nodes[0], 1);
5418 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5419 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5420 check_added_monitors!(nodes[1], 1);
5422 let starting_block = nodes[1].best_block_info();
5423 let mut block = Block {
5424 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5427 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5428 connect_block(&nodes[1], &block);
5429 block.header.prev_blockhash = block.block_hash();
5431 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5432 check_closed_broadcast!(nodes[1], true);
5433 check_added_monitors!(nodes[1], 1);
5434 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5437 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5438 let chanmon_cfgs = create_chanmon_cfgs(2);
5439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5441 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5442 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5444 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5445 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5446 check_added_monitors!(nodes[0], 1);
5448 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5450 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5451 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5452 // to "time out" the HTLC.
5454 let starting_block = nodes[1].best_block_info();
5455 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5457 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5458 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5459 header.prev_blockhash = header.block_hash();
5461 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5462 check_closed_broadcast!(nodes[0], true);
5463 check_added_monitors!(nodes[0], 1);
5464 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5467 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5468 let chanmon_cfgs = create_chanmon_cfgs(3);
5469 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5470 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5471 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5472 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5474 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5475 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5476 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5477 // actually revoked.
5478 let htlc_value = if use_dust { 50000 } else { 3000000 };
5479 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5480 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5481 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5482 check_added_monitors!(nodes[1], 1);
5484 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5485 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5486 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5487 check_added_monitors!(nodes[0], 1);
5488 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5490 check_added_monitors!(nodes[1], 1);
5491 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5492 check_added_monitors!(nodes[1], 1);
5493 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5495 if check_revoke_no_close {
5496 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5497 check_added_monitors!(nodes[0], 1);
5500 let starting_block = nodes[1].best_block_info();
5501 let mut block = Block {
5502 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5505 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5506 connect_block(&nodes[0], &block);
5507 block.header.prev_blockhash = block.block_hash();
5509 if !check_revoke_no_close {
5510 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5511 check_closed_broadcast!(nodes[0], true);
5512 check_added_monitors!(nodes[0], 1);
5513 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5515 expect_payment_failed!(nodes[0], our_payment_hash, true);
5519 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5520 // There are only a few cases to test here:
5521 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5522 // broadcastable commitment transactions result in channel closure,
5523 // * its included in an unrevoked-but-previous remote commitment transaction,
5524 // * its included in the latest remote or local commitment transactions.
5525 // We test each of the three possible commitment transactions individually and use both dust and
5527 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5528 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5529 // tested for at least one of the cases in other tests.
5531 fn htlc_claim_single_commitment_only_a() {
5532 do_htlc_claim_local_commitment_only(true);
5533 do_htlc_claim_local_commitment_only(false);
5535 do_htlc_claim_current_remote_commitment_only(true);
5536 do_htlc_claim_current_remote_commitment_only(false);
5540 fn htlc_claim_single_commitment_only_b() {
5541 do_htlc_claim_previous_remote_commitment_only(true, false);
5542 do_htlc_claim_previous_remote_commitment_only(false, false);
5543 do_htlc_claim_previous_remote_commitment_only(true, true);
5544 do_htlc_claim_previous_remote_commitment_only(false, true);
5549 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5550 let chanmon_cfgs = create_chanmon_cfgs(2);
5551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5553 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5554 // Force duplicate randomness for every get-random call
5555 for node in nodes.iter() {
5556 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5559 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5560 let channel_value_satoshis=10000;
5561 let push_msat=10001;
5562 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5563 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5564 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5565 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5567 // Create a second channel with the same random values. This used to panic due to a colliding
5568 // channel_id, but now panics due to a colliding outbound SCID alias.
5569 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5573 fn bolt2_open_channel_sending_node_checks_part2() {
5574 let chanmon_cfgs = create_chanmon_cfgs(2);
5575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5579 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5580 let channel_value_satoshis=2^24;
5581 let push_msat=10001;
5582 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5584 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5585 let channel_value_satoshis=10000;
5586 // Test when push_msat is equal to 1000 * funding_satoshis.
5587 let push_msat=1000*channel_value_satoshis+1;
5588 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5590 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5591 let channel_value_satoshis=10000;
5592 let push_msat=10001;
5593 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
5594 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5595 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5597 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5598 // 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
5599 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5601 // 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.
5602 assert!(BREAKDOWN_TIMEOUT>0);
5603 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5605 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5606 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5607 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5609 // 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.
5610 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5611 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5612 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5613 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5614 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5618 fn bolt2_open_channel_sane_dust_limit() {
5619 let chanmon_cfgs = create_chanmon_cfgs(2);
5620 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5621 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5622 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5624 let channel_value_satoshis=1000000;
5625 let push_msat=10001;
5626 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5627 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5628 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5629 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5631 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5632 let events = nodes[1].node.get_and_clear_pending_msg_events();
5633 let err_msg = match events[0] {
5634 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5637 _ => panic!("Unexpected event"),
5639 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5642 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5643 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5644 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5645 // is no longer affordable once it's freed.
5647 fn test_fail_holding_cell_htlc_upon_free() {
5648 let chanmon_cfgs = create_chanmon_cfgs(2);
5649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5651 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5652 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5654 // First nodes[0] generates an update_fee, setting the channel's
5655 // pending_update_fee.
5657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5658 *feerate_lock += 20;
5660 nodes[0].node.timer_tick_occurred();
5661 check_added_monitors!(nodes[0], 1);
5663 let events = nodes[0].node.get_and_clear_pending_msg_events();
5664 assert_eq!(events.len(), 1);
5665 let (update_msg, commitment_signed) = match events[0] {
5666 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5667 (update_fee.as_ref(), commitment_signed)
5669 _ => panic!("Unexpected event"),
5672 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5674 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5675 let channel_reserve = chan_stat.channel_reserve_msat;
5676 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5677 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5679 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5680 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5681 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5683 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5684 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5685 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5686 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5688 // Flush the pending fee update.
5689 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5690 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5691 check_added_monitors!(nodes[1], 1);
5692 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5693 check_added_monitors!(nodes[0], 1);
5695 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5696 // HTLC, but now that the fee has been raised the payment will now fail, causing
5697 // us to surface its failure to the user.
5698 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5699 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5700 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);
5701 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 {}",
5702 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5703 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5705 // Check that the payment failed to be sent out.
5706 let events = nodes[0].node.get_and_clear_pending_events();
5707 assert_eq!(events.len(), 2);
5709 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5710 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5711 assert_eq!(our_payment_hash.clone(), *payment_hash);
5712 assert_eq!(*payment_failed_permanently, false);
5713 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5715 _ => panic!("Unexpected event"),
5718 &Event::PaymentFailed { ref payment_hash, .. } => {
5719 assert_eq!(our_payment_hash.clone(), *payment_hash);
5721 _ => panic!("Unexpected event"),
5725 // Test that if multiple HTLCs are released from the holding cell and one is
5726 // valid but the other is no longer valid upon release, the valid HTLC can be
5727 // successfully completed while the other one fails as expected.
5729 fn test_free_and_fail_holding_cell_htlcs() {
5730 let chanmon_cfgs = create_chanmon_cfgs(2);
5731 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5732 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5733 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5734 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5736 // First nodes[0] generates an update_fee, setting the channel's
5737 // pending_update_fee.
5739 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5740 *feerate_lock += 200;
5742 nodes[0].node.timer_tick_occurred();
5743 check_added_monitors!(nodes[0], 1);
5745 let events = nodes[0].node.get_and_clear_pending_msg_events();
5746 assert_eq!(events.len(), 1);
5747 let (update_msg, commitment_signed) = match events[0] {
5748 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5749 (update_fee.as_ref(), commitment_signed)
5751 _ => panic!("Unexpected event"),
5754 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5756 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5757 let channel_reserve = chan_stat.channel_reserve_msat;
5758 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5759 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5761 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5763 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5764 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5765 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5767 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5768 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5769 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5770 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5771 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5772 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5773 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5774 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5776 // Flush the pending fee update.
5777 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5778 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5779 check_added_monitors!(nodes[1], 1);
5780 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5781 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5782 check_added_monitors!(nodes[0], 2);
5784 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5785 // but now that the fee has been raised the second payment will now fail, causing us
5786 // to surface its failure to the user. The first payment should succeed.
5787 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5788 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5789 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);
5790 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 {}",
5791 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5792 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5794 // Check that the second payment failed to be sent out.
5795 let events = nodes[0].node.get_and_clear_pending_events();
5796 assert_eq!(events.len(), 2);
5798 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5799 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5800 assert_eq!(payment_hash_2.clone(), *payment_hash);
5801 assert_eq!(*payment_failed_permanently, false);
5802 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5804 _ => panic!("Unexpected event"),
5807 &Event::PaymentFailed { ref payment_hash, .. } => {
5808 assert_eq!(payment_hash_2.clone(), *payment_hash);
5810 _ => panic!("Unexpected event"),
5813 // Complete the first payment and the RAA from the fee update.
5814 let (payment_event, send_raa_event) = {
5815 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5816 assert_eq!(msgs.len(), 2);
5817 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5819 let raa = match send_raa_event {
5820 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5821 _ => panic!("Unexpected event"),
5823 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5824 check_added_monitors!(nodes[1], 1);
5825 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5826 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5827 let events = nodes[1].node.get_and_clear_pending_events();
5828 assert_eq!(events.len(), 1);
5830 Event::PendingHTLCsForwardable { .. } => {},
5831 _ => panic!("Unexpected event"),
5833 nodes[1].node.process_pending_htlc_forwards();
5834 let events = nodes[1].node.get_and_clear_pending_events();
5835 assert_eq!(events.len(), 1);
5837 Event::PaymentClaimable { .. } => {},
5838 _ => panic!("Unexpected event"),
5840 nodes[1].node.claim_funds(payment_preimage_1);
5841 check_added_monitors!(nodes[1], 1);
5842 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5844 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5845 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5846 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5847 expect_payment_sent!(nodes[0], payment_preimage_1);
5850 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5851 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5852 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5855 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5856 let chanmon_cfgs = create_chanmon_cfgs(3);
5857 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5858 // When this test was written, the default base fee floated based on the HTLC count.
5859 // It is now fixed, so we simply set the fee to the expected value here.
5860 let mut config = test_default_channel_config();
5861 config.channel_config.forwarding_fee_base_msat = 196;
5862 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5863 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5864 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5865 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5867 // First nodes[1] generates an update_fee, setting the channel's
5868 // pending_update_fee.
5870 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5871 *feerate_lock += 20;
5873 nodes[1].node.timer_tick_occurred();
5874 check_added_monitors!(nodes[1], 1);
5876 let events = nodes[1].node.get_and_clear_pending_msg_events();
5877 assert_eq!(events.len(), 1);
5878 let (update_msg, commitment_signed) = match events[0] {
5879 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5880 (update_fee.as_ref(), commitment_signed)
5882 _ => panic!("Unexpected event"),
5885 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5887 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5888 let channel_reserve = chan_stat.channel_reserve_msat;
5889 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5890 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5892 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5894 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5895 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5896 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5897 let payment_event = {
5898 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5899 check_added_monitors!(nodes[0], 1);
5901 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5902 assert_eq!(events.len(), 1);
5904 SendEvent::from_event(events.remove(0))
5906 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5907 check_added_monitors!(nodes[1], 0);
5908 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5909 expect_pending_htlcs_forwardable!(nodes[1]);
5911 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5912 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5914 // Flush the pending fee update.
5915 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5916 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5917 check_added_monitors!(nodes[2], 1);
5918 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5919 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5920 check_added_monitors!(nodes[1], 2);
5922 // A final RAA message is generated to finalize the fee update.
5923 let events = nodes[1].node.get_and_clear_pending_msg_events();
5924 assert_eq!(events.len(), 1);
5926 let raa_msg = match &events[0] {
5927 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5930 _ => panic!("Unexpected event"),
5933 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5934 check_added_monitors!(nodes[2], 1);
5935 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5937 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5938 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5939 assert_eq!(process_htlc_forwards_event.len(), 2);
5940 match &process_htlc_forwards_event[0] {
5941 &Event::PendingHTLCsForwardable { .. } => {},
5942 _ => panic!("Unexpected event"),
5945 // In response, we call ChannelManager's process_pending_htlc_forwards
5946 nodes[1].node.process_pending_htlc_forwards();
5947 check_added_monitors!(nodes[1], 1);
5949 // This causes the HTLC to be failed backwards.
5950 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5951 assert_eq!(fail_event.len(), 1);
5952 let (fail_msg, commitment_signed) = match &fail_event[0] {
5953 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5954 assert_eq!(updates.update_add_htlcs.len(), 0);
5955 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5956 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5957 assert_eq!(updates.update_fail_htlcs.len(), 1);
5958 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5960 _ => panic!("Unexpected event"),
5963 // Pass the failure messages back to nodes[0].
5964 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5965 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5967 // Complete the HTLC failure+removal process.
5968 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5969 check_added_monitors!(nodes[0], 1);
5970 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5971 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5972 check_added_monitors!(nodes[1], 2);
5973 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5974 assert_eq!(final_raa_event.len(), 1);
5975 let raa = match &final_raa_event[0] {
5976 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5977 _ => panic!("Unexpected event"),
5979 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5980 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5981 check_added_monitors!(nodes[0], 1);
5984 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5985 // 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.
5986 //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.
5989 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5990 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5991 let chanmon_cfgs = create_chanmon_cfgs(2);
5992 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5993 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5994 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5995 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5997 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5998 route.paths[0][0].fee_msat = 100;
6000 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6001 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6002 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6003 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6007 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6008 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6009 let chanmon_cfgs = create_chanmon_cfgs(2);
6010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6012 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6013 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6015 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6016 route.paths[0][0].fee_msat = 0;
6017 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6018 assert_eq!(err, "Cannot send 0-msat HTLC"));
6020 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6021 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6025 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6026 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6027 let chanmon_cfgs = create_chanmon_cfgs(2);
6028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6030 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6031 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6033 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6034 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6035 check_added_monitors!(nodes[0], 1);
6036 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6037 updates.update_add_htlcs[0].amount_msat = 0;
6039 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6040 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6041 check_closed_broadcast!(nodes[1], true).unwrap();
6042 check_added_monitors!(nodes[1], 1);
6043 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6047 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6048 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6049 //It is enforced when constructing a route.
6050 let chanmon_cfgs = create_chanmon_cfgs(2);
6051 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6052 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6053 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6054 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6056 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6057 .with_features(nodes[1].node.invoice_features());
6058 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6059 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6060 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::InvalidRoute { ref err },
6061 assert_eq!(err, &"Channel CLTV overflowed?"));
6065 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6066 //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.
6067 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6068 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6069 let chanmon_cfgs = create_chanmon_cfgs(2);
6070 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6071 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6072 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6073 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6074 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6075 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6077 for i in 0..max_accepted_htlcs {
6078 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6079 let payment_event = {
6080 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6081 check_added_monitors!(nodes[0], 1);
6083 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6084 assert_eq!(events.len(), 1);
6085 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6086 assert_eq!(htlcs[0].htlc_id, i);
6090 SendEvent::from_event(events.remove(0))
6092 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6093 check_added_monitors!(nodes[1], 0);
6094 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6096 expect_pending_htlcs_forwardable!(nodes[1]);
6097 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6099 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6100 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6101 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6103 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6104 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6108 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6109 //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.
6110 let chanmon_cfgs = create_chanmon_cfgs(2);
6111 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6112 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6113 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6114 let channel_value = 100000;
6115 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6116 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6118 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6120 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6121 // Manually create a route over our max in flight (which our router normally automatically
6123 route.paths[0][0].fee_msat = max_in_flight + 1;
6124 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)), true, APIError::ChannelUnavailable { ref err },
6125 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)));
6127 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6128 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);
6130 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6133 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6135 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6136 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6137 let chanmon_cfgs = create_chanmon_cfgs(2);
6138 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6139 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6140 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6141 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6142 let htlc_minimum_msat: u64;
6144 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6145 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6146 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6147 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6150 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6151 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6152 check_added_monitors!(nodes[0], 1);
6153 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6154 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6155 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6156 assert!(nodes[1].node.list_channels().is_empty());
6157 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6158 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()));
6159 check_added_monitors!(nodes[1], 1);
6160 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6164 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6165 //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
6166 let chanmon_cfgs = create_chanmon_cfgs(2);
6167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6169 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6170 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6172 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6173 let channel_reserve = chan_stat.channel_reserve_msat;
6174 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6175 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6176 // The 2* and +1 are for the fee spike reserve.
6177 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6179 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6180 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6181 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6182 check_added_monitors!(nodes[0], 1);
6183 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6185 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6186 // at this time channel-initiatee receivers are not required to enforce that senders
6187 // respect the fee_spike_reserve.
6188 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6189 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_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
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_check_max_htlc_limit() {
6200 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6201 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6202 let chanmon_cfgs = create_chanmon_cfgs(2);
6203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6205 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6206 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6208 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6209 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6210 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6211 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6212 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6213 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6215 let mut msg = msgs::UpdateAddHTLC {
6219 payment_hash: our_payment_hash,
6220 cltv_expiry: htlc_cltv,
6221 onion_routing_packet: onion_packet.clone(),
6224 for i in 0..super::channel::OUR_MAX_HTLCS {
6225 msg.htlc_id = i as u64;
6226 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6228 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6231 assert!(nodes[1].node.list_channels().is_empty());
6232 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6233 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6234 check_added_monitors!(nodes[1], 1);
6235 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6239 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6240 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6241 let chanmon_cfgs = create_chanmon_cfgs(2);
6242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6244 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6245 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6247 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6248 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6249 check_added_monitors!(nodes[0], 1);
6250 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6251 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;
6252 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6254 assert!(nodes[1].node.list_channels().is_empty());
6255 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6256 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6257 check_added_monitors!(nodes[1], 1);
6258 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6262 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6263 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6264 let chanmon_cfgs = create_chanmon_cfgs(2);
6265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6267 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6269 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6270 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6271 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6272 check_added_monitors!(nodes[0], 1);
6273 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6274 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6275 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6277 assert!(nodes[1].node.list_channels().is_empty());
6278 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6279 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6280 check_added_monitors!(nodes[1], 1);
6281 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6285 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6286 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6287 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6288 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6289 let chanmon_cfgs = create_chanmon_cfgs(2);
6290 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6291 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6292 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6294 create_announced_chan_between_nodes(&nodes, 0, 1);
6295 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6296 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6297 check_added_monitors!(nodes[0], 1);
6298 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6299 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6301 //Disconnect and Reconnect
6302 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6303 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6304 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();
6305 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6306 assert_eq!(reestablish_1.len(), 1);
6307 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();
6308 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6309 assert_eq!(reestablish_2.len(), 1);
6310 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6311 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6312 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6313 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6316 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6317 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6318 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6319 check_added_monitors!(nodes[1], 1);
6320 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6324 assert!(nodes[1].node.list_channels().is_empty());
6325 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6326 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6327 check_added_monitors!(nodes[1], 1);
6328 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6332 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6333 //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.
6335 let chanmon_cfgs = create_chanmon_cfgs(2);
6336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6339 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6340 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6341 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6343 check_added_monitors!(nodes[0], 1);
6344 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6345 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6347 let update_msg = msgs::UpdateFulfillHTLC{
6350 payment_preimage: our_payment_preimage,
6353 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6355 assert!(nodes[0].node.list_channels().is_empty());
6356 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6357 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()));
6358 check_added_monitors!(nodes[0], 1);
6359 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6363 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6364 //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.
6366 let chanmon_cfgs = create_chanmon_cfgs(2);
6367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6370 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6372 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6373 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6374 check_added_monitors!(nodes[0], 1);
6375 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6376 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6378 let update_msg = msgs::UpdateFailHTLC{
6381 reason: msgs::OnionErrorPacket { data: Vec::new()},
6384 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6386 assert!(nodes[0].node.list_channels().is_empty());
6387 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6388 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()));
6389 check_added_monitors!(nodes[0], 1);
6390 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6394 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6395 //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.
6397 let chanmon_cfgs = create_chanmon_cfgs(2);
6398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6401 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6403 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6404 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6405 check_added_monitors!(nodes[0], 1);
6406 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6407 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6408 let update_msg = msgs::UpdateFailMalformedHTLC{
6411 sha256_of_onion: [1; 32],
6412 failure_code: 0x8000,
6415 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6417 assert!(nodes[0].node.list_channels().is_empty());
6418 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6419 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()));
6420 check_added_monitors!(nodes[0], 1);
6421 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6425 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6426 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6428 let chanmon_cfgs = create_chanmon_cfgs(2);
6429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6432 create_announced_chan_between_nodes(&nodes, 0, 1);
6434 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6436 nodes[1].node.claim_funds(our_payment_preimage);
6437 check_added_monitors!(nodes[1], 1);
6438 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6440 let events = nodes[1].node.get_and_clear_pending_msg_events();
6441 assert_eq!(events.len(), 1);
6442 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6444 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, .. } } => {
6445 assert!(update_add_htlcs.is_empty());
6446 assert_eq!(update_fulfill_htlcs.len(), 1);
6447 assert!(update_fail_htlcs.is_empty());
6448 assert!(update_fail_malformed_htlcs.is_empty());
6449 assert!(update_fee.is_none());
6450 update_fulfill_htlcs[0].clone()
6452 _ => panic!("Unexpected event"),
6456 update_fulfill_msg.htlc_id = 1;
6458 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6460 assert!(nodes[0].node.list_channels().is_empty());
6461 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6462 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
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_wrong_preimage() {
6469 //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.
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.payment_preimage = PaymentPreimage([1; 32]);
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!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
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_missing_badonion_bit_for_malformed_htlc_message() {
6512 //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.
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 mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6518 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6520 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6521 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6522 check_added_monitors!(nodes[0], 1);
6524 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6525 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6527 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6528 check_added_monitors!(nodes[1], 0);
6529 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6531 let events = nodes[1].node.get_and_clear_pending_msg_events();
6533 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6535 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, .. } } => {
6536 assert!(update_add_htlcs.is_empty());
6537 assert!(update_fulfill_htlcs.is_empty());
6538 assert!(update_fail_htlcs.is_empty());
6539 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6540 assert!(update_fee.is_none());
6541 update_fail_malformed_htlcs[0].clone()
6543 _ => panic!("Unexpected event"),
6546 update_msg.failure_code &= !0x8000;
6547 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6549 assert!(nodes[0].node.list_channels().is_empty());
6550 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6551 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6552 check_added_monitors!(nodes[0], 1);
6553 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6557 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6558 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6559 // * 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.
6561 let chanmon_cfgs = create_chanmon_cfgs(3);
6562 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6563 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6564 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6565 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6566 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6568 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6571 let mut payment_event = {
6572 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6573 check_added_monitors!(nodes[0], 1);
6574 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6575 assert_eq!(events.len(), 1);
6576 SendEvent::from_event(events.remove(0))
6578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6579 check_added_monitors!(nodes[1], 0);
6580 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6581 expect_pending_htlcs_forwardable!(nodes[1]);
6582 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6583 assert_eq!(events_2.len(), 1);
6584 check_added_monitors!(nodes[1], 1);
6585 payment_event = SendEvent::from_event(events_2.remove(0));
6586 assert_eq!(payment_event.msgs.len(), 1);
6589 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6590 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6591 check_added_monitors!(nodes[2], 0);
6592 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6594 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6595 assert_eq!(events_3.len(), 1);
6596 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6598 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 } } => {
6599 assert!(update_add_htlcs.is_empty());
6600 assert!(update_fulfill_htlcs.is_empty());
6601 assert!(update_fail_htlcs.is_empty());
6602 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6603 assert!(update_fee.is_none());
6604 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6606 _ => panic!("Unexpected event"),
6610 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6612 check_added_monitors!(nodes[1], 0);
6613 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6614 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 }]);
6615 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6616 assert_eq!(events_4.len(), 1);
6618 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6620 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, .. } } => {
6621 assert!(update_add_htlcs.is_empty());
6622 assert!(update_fulfill_htlcs.is_empty());
6623 assert_eq!(update_fail_htlcs.len(), 1);
6624 assert!(update_fail_malformed_htlcs.is_empty());
6625 assert!(update_fee.is_none());
6627 _ => panic!("Unexpected event"),
6630 check_added_monitors!(nodes[1], 1);
6634 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6635 let chanmon_cfgs = create_chanmon_cfgs(3);
6636 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6637 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6638 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6639 create_announced_chan_between_nodes(&nodes, 0, 1);
6640 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6642 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6645 let mut payment_event = {
6646 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6647 check_added_monitors!(nodes[0], 1);
6648 SendEvent::from_node(&nodes[0])
6651 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6652 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6653 expect_pending_htlcs_forwardable!(nodes[1]);
6654 check_added_monitors!(nodes[1], 1);
6655 payment_event = SendEvent::from_node(&nodes[1]);
6656 assert_eq!(payment_event.msgs.len(), 1);
6659 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6660 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6661 check_added_monitors!(nodes[2], 0);
6662 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6664 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6665 assert_eq!(events_3.len(), 1);
6667 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6668 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6669 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6670 update_msg.failure_code |= 0x2000;
6672 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6673 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6675 _ => panic!("Unexpected event"),
6678 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6679 vec![HTLCDestination::NextHopChannel {
6680 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6681 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6682 assert_eq!(events_4.len(), 1);
6683 check_added_monitors!(nodes[1], 1);
6686 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6687 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6688 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6690 _ => panic!("Unexpected event"),
6693 let events_5 = nodes[0].node.get_and_clear_pending_events();
6694 assert_eq!(events_5.len(), 2);
6696 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6697 // the node originating the error to its next hop.
6699 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6701 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6702 assert!(is_permanent);
6703 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6705 _ => panic!("Unexpected event"),
6708 Event::PaymentFailed { payment_hash, .. } => {
6709 assert_eq!(payment_hash, our_payment_hash);
6711 _ => panic!("Unexpected event"),
6714 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6717 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6718 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6719 // 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
6720 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6722 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6723 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6726 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6727 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6729 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6730 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6732 // We route 2 dust-HTLCs between A and B
6733 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6734 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6735 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6737 // Cache one local commitment tx as previous
6738 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6740 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6741 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6742 check_added_monitors!(nodes[1], 0);
6743 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6744 check_added_monitors!(nodes[1], 1);
6746 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6747 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6748 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6749 check_added_monitors!(nodes[0], 1);
6751 // Cache one local commitment tx as lastest
6752 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6754 let events = nodes[0].node.get_and_clear_pending_msg_events();
6756 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6757 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6759 _ => panic!("Unexpected event"),
6762 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6763 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6765 _ => panic!("Unexpected event"),
6768 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6769 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6770 if announce_latest {
6771 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6773 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6776 check_closed_broadcast!(nodes[0], true);
6777 check_added_monitors!(nodes[0], 1);
6778 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6780 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6781 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6782 let events = nodes[0].node.get_and_clear_pending_events();
6783 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6784 assert_eq!(events.len(), 4);
6785 let mut first_failed = false;
6786 for event in events {
6788 Event::PaymentPathFailed { payment_hash, .. } => {
6789 if payment_hash == payment_hash_1 {
6790 assert!(!first_failed);
6791 first_failed = true;
6793 assert_eq!(payment_hash, payment_hash_2);
6796 Event::PaymentFailed { .. } => {}
6797 _ => panic!("Unexpected event"),
6803 fn test_failure_delay_dust_htlc_local_commitment() {
6804 do_test_failure_delay_dust_htlc_local_commitment(true);
6805 do_test_failure_delay_dust_htlc_local_commitment(false);
6808 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6809 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6810 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6811 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6812 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6813 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6814 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6816 let chanmon_cfgs = create_chanmon_cfgs(3);
6817 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6818 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6819 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6820 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6822 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6823 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6825 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6826 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6828 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6829 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6831 // We revoked bs_commitment_tx
6833 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6834 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6837 let mut timeout_tx = Vec::new();
6839 // We fail dust-HTLC 1 by broadcast of local commitment tx
6840 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6841 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6842 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6843 expect_payment_failed!(nodes[0], dust_hash, false);
6845 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6846 check_closed_broadcast!(nodes[0], true);
6847 check_added_monitors!(nodes[0], 1);
6848 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6849 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6850 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6851 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6852 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6853 mine_transaction(&nodes[0], &timeout_tx[0]);
6854 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6855 expect_payment_failed!(nodes[0], non_dust_hash, false);
6857 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6858 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6859 check_closed_broadcast!(nodes[0], true);
6860 check_added_monitors!(nodes[0], 1);
6861 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6862 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6864 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6865 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6866 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6867 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6868 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6869 // dust HTLC should have been failed.
6870 expect_payment_failed!(nodes[0], dust_hash, false);
6873 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6875 assert_eq!(timeout_tx[0].lock_time.0, 12);
6877 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6878 mine_transaction(&nodes[0], &timeout_tx[0]);
6879 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6880 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6881 expect_payment_failed!(nodes[0], non_dust_hash, false);
6886 fn test_sweep_outbound_htlc_failure_update() {
6887 do_test_sweep_outbound_htlc_failure_update(false, true);
6888 do_test_sweep_outbound_htlc_failure_update(false, false);
6889 do_test_sweep_outbound_htlc_failure_update(true, false);
6893 fn test_user_configurable_csv_delay() {
6894 // We test our channel constructors yield errors when we pass them absurd csv delay
6896 let mut low_our_to_self_config = UserConfig::default();
6897 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6898 let mut high_their_to_self_config = UserConfig::default();
6899 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6900 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6901 let chanmon_cfgs = create_chanmon_cfgs(2);
6902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6906 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6907 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6908 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6909 &low_our_to_self_config, 0, 42)
6912 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())); },
6913 _ => panic!("Unexpected event"),
6915 } else { assert!(false) }
6917 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6918 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6919 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6920 open_channel.to_self_delay = 200;
6921 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6922 &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,
6923 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6926 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())); },
6927 _ => panic!("Unexpected event"),
6929 } else { assert!(false); }
6931 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6932 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6933 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()));
6934 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6935 accept_channel.to_self_delay = 200;
6936 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6938 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6940 &ErrorAction::SendErrorMessage { ref msg } => {
6941 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()));
6942 reason_msg = msg.data.clone();
6946 } else { panic!(); }
6947 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6949 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6950 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6951 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6952 open_channel.to_self_delay = 200;
6953 if let Err(error) = Channel::new_from_req(&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[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
6955 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6958 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())); },
6959 _ => panic!("Unexpected event"),
6961 } else { assert!(false); }
6965 fn test_check_htlc_underpaying() {
6966 // Send payment through A -> B but A is maliciously
6967 // sending a probe payment (i.e less than expected value0
6968 // to B, B should refuse payment.
6970 let chanmon_cfgs = create_chanmon_cfgs(2);
6971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6973 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6975 // Create some initial channels
6976 create_announced_chan_between_nodes(&nodes, 0, 1);
6978 let scorer = test_utils::TestScorer::new();
6979 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6980 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6981 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
6982 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6983 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6984 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6985 check_added_monitors!(nodes[0], 1);
6987 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6988 assert_eq!(events.len(), 1);
6989 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6990 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6991 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6993 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6994 // and then will wait a second random delay before failing the HTLC back:
6995 expect_pending_htlcs_forwardable!(nodes[1]);
6996 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6998 // Node 3 is expecting payment of 100_000 but received 10_000,
6999 // it should fail htlc like we didn't know the preimage.
7000 nodes[1].node.process_pending_htlc_forwards();
7002 let events = nodes[1].node.get_and_clear_pending_msg_events();
7003 assert_eq!(events.len(), 1);
7004 let (update_fail_htlc, commitment_signed) = match events[0] {
7005 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 } } => {
7006 assert!(update_add_htlcs.is_empty());
7007 assert!(update_fulfill_htlcs.is_empty());
7008 assert_eq!(update_fail_htlcs.len(), 1);
7009 assert!(update_fail_malformed_htlcs.is_empty());
7010 assert!(update_fee.is_none());
7011 (update_fail_htlcs[0].clone(), commitment_signed)
7013 _ => panic!("Unexpected event"),
7015 check_added_monitors!(nodes[1], 1);
7017 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7018 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7020 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7021 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7022 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7023 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7027 fn test_announce_disable_channels() {
7028 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7029 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7031 let chanmon_cfgs = create_chanmon_cfgs(2);
7032 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7033 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7034 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7036 create_announced_chan_between_nodes(&nodes, 0, 1);
7037 create_announced_chan_between_nodes(&nodes, 1, 0);
7038 create_announced_chan_between_nodes(&nodes, 0, 1);
7041 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7042 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7044 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7045 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7046 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7047 assert_eq!(msg_events.len(), 3);
7048 let mut chans_disabled = HashMap::new();
7049 for e in msg_events {
7051 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7052 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7053 // Check that each channel gets updated exactly once
7054 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7055 panic!("Generated ChannelUpdate for wrong chan!");
7058 _ => panic!("Unexpected event"),
7062 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();
7063 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7064 assert_eq!(reestablish_1.len(), 3);
7065 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();
7066 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7067 assert_eq!(reestablish_2.len(), 3);
7069 // Reestablish chan_1
7070 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7071 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7072 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7073 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7074 // Reestablish chan_2
7075 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7076 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7077 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7078 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7079 // Reestablish chan_3
7080 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7081 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7082 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7083 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7085 nodes[0].node.timer_tick_occurred();
7086 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7087 nodes[0].node.timer_tick_occurred();
7088 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7089 assert_eq!(msg_events.len(), 3);
7090 for e in msg_events {
7092 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7093 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7094 match chans_disabled.remove(&msg.contents.short_channel_id) {
7095 // Each update should have a higher timestamp than the previous one, replacing
7097 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7098 None => panic!("Generated ChannelUpdate for wrong chan!"),
7101 _ => panic!("Unexpected event"),
7104 // Check that each channel gets updated exactly once
7105 assert!(chans_disabled.is_empty());
7109 fn test_bump_penalty_txn_on_revoked_commitment() {
7110 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7111 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7113 let chanmon_cfgs = create_chanmon_cfgs(2);
7114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7116 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7118 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7120 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7121 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7122 .with_features(nodes[0].node.invoice_features());
7123 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7124 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7126 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7127 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7128 assert_eq!(revoked_txn[0].output.len(), 4);
7129 assert_eq!(revoked_txn[0].input.len(), 1);
7130 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7131 let revoked_txid = revoked_txn[0].txid();
7133 let mut penalty_sum = 0;
7134 for outp in revoked_txn[0].output.iter() {
7135 if outp.script_pubkey.is_v0_p2wsh() {
7136 penalty_sum += outp.value;
7140 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7141 let header_114 = connect_blocks(&nodes[1], 14);
7143 // Actually revoke tx by claiming a HTLC
7144 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7145 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7146 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7147 check_added_monitors!(nodes[1], 1);
7149 // One or more justice tx should have been broadcast, check it
7153 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7154 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7155 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7156 assert_eq!(node_txn[0].output.len(), 1);
7157 check_spends!(node_txn[0], revoked_txn[0]);
7158 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7159 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7160 penalty_1 = node_txn[0].txid();
7164 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7165 connect_blocks(&nodes[1], 15);
7166 let mut penalty_2 = penalty_1;
7167 let mut feerate_2 = 0;
7169 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7170 assert_eq!(node_txn.len(), 1);
7171 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7172 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7173 assert_eq!(node_txn[0].output.len(), 1);
7174 check_spends!(node_txn[0], revoked_txn[0]);
7175 penalty_2 = node_txn[0].txid();
7176 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7177 assert_ne!(penalty_2, penalty_1);
7178 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7179 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7180 // Verify 25% bump heuristic
7181 assert!(feerate_2 * 100 >= feerate_1 * 125);
7185 assert_ne!(feerate_2, 0);
7187 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7188 connect_blocks(&nodes[1], 1);
7190 let mut feerate_3 = 0;
7192 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7193 assert_eq!(node_txn.len(), 1);
7194 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7195 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7196 assert_eq!(node_txn[0].output.len(), 1);
7197 check_spends!(node_txn[0], revoked_txn[0]);
7198 penalty_3 = node_txn[0].txid();
7199 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7200 assert_ne!(penalty_3, penalty_2);
7201 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7202 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7203 // Verify 25% bump heuristic
7204 assert!(feerate_3 * 100 >= feerate_2 * 125);
7208 assert_ne!(feerate_3, 0);
7210 nodes[1].node.get_and_clear_pending_events();
7211 nodes[1].node.get_and_clear_pending_msg_events();
7215 fn test_bump_penalty_txn_on_revoked_htlcs() {
7216 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7217 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7219 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7220 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7221 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7222 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7223 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7225 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7226 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7227 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7228 let scorer = test_utils::TestScorer::new();
7229 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7230 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7231 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7232 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7233 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7234 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7235 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7236 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7238 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7239 assert_eq!(revoked_local_txn[0].input.len(), 1);
7240 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7242 // Revoke local commitment tx
7243 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7245 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7246 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7247 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7248 check_closed_broadcast!(nodes[1], true);
7249 check_added_monitors!(nodes[1], 1);
7250 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7251 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7253 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7254 assert_eq!(revoked_htlc_txn.len(), 2);
7256 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7257 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7258 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7260 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7261 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7262 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7263 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7265 // Broadcast set of revoked txn on A
7266 let hash_128 = connect_blocks(&nodes[0], 40);
7267 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7268 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7269 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7270 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7271 let events = nodes[0].node.get_and_clear_pending_events();
7272 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7273 match events.last().unwrap() {
7274 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7275 _ => panic!("Unexpected event"),
7281 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7282 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7283 // Verify claim tx are spending revoked HTLC txn
7285 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7286 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7287 // which are included in the same block (they are broadcasted because we scan the
7288 // transactions linearly and generate claims as we go, they likely should be removed in the
7290 assert_eq!(node_txn[0].input.len(), 1);
7291 check_spends!(node_txn[0], revoked_local_txn[0]);
7292 assert_eq!(node_txn[1].input.len(), 1);
7293 check_spends!(node_txn[1], revoked_local_txn[0]);
7294 assert_eq!(node_txn[2].input.len(), 1);
7295 check_spends!(node_txn[2], revoked_local_txn[0]);
7297 // Each of the three justice transactions claim a separate (single) output of the three
7298 // available, which we check here:
7299 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7300 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7301 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7303 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7304 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7306 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7307 // output, checked above).
7308 assert_eq!(node_txn[3].input.len(), 2);
7309 assert_eq!(node_txn[3].output.len(), 1);
7310 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7312 first = node_txn[3].txid();
7313 // Store both feerates for later comparison
7314 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7315 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7316 penalty_txn = vec![node_txn[2].clone()];
7320 // Connect one more block to see if bumped penalty are issued for HTLC txn
7321 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7322 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7323 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7324 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7326 // Few more blocks to confirm penalty txn
7327 connect_blocks(&nodes[0], 4);
7328 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7329 let header_144 = connect_blocks(&nodes[0], 9);
7331 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7332 assert_eq!(node_txn.len(), 1);
7334 assert_eq!(node_txn[0].input.len(), 2);
7335 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7336 // Verify bumped tx is different and 25% bump heuristic
7337 assert_ne!(first, node_txn[0].txid());
7338 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7339 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7340 assert!(feerate_2 * 100 > feerate_1 * 125);
7341 let txn = vec![node_txn[0].clone()];
7345 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7346 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7347 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7348 connect_blocks(&nodes[0], 20);
7350 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7351 // We verify than no new transaction has been broadcast because previously
7352 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7353 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7354 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7355 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7356 // up bumped justice generation.
7357 assert_eq!(node_txn.len(), 0);
7360 check_closed_broadcast!(nodes[0], true);
7361 check_added_monitors!(nodes[0], 1);
7365 fn test_bump_penalty_txn_on_remote_commitment() {
7366 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7367 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7370 // Provide preimage for one
7371 // Check aggregation
7373 let chanmon_cfgs = create_chanmon_cfgs(2);
7374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7378 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7379 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7380 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7382 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7383 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7384 assert_eq!(remote_txn[0].output.len(), 4);
7385 assert_eq!(remote_txn[0].input.len(), 1);
7386 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7388 // Claim a HTLC without revocation (provide B monitor with preimage)
7389 nodes[1].node.claim_funds(payment_preimage);
7390 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7391 mine_transaction(&nodes[1], &remote_txn[0]);
7392 check_added_monitors!(nodes[1], 2);
7393 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7395 // One or more claim tx should have been broadcast, check it
7399 let feerate_timeout;
7400 let feerate_preimage;
7402 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7403 // 3 transactions including:
7404 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7405 assert_eq!(node_txn.len(), 3);
7406 assert_eq!(node_txn[0].input.len(), 1);
7407 assert_eq!(node_txn[1].input.len(), 1);
7408 assert_eq!(node_txn[2].input.len(), 1);
7409 check_spends!(node_txn[0], remote_txn[0]);
7410 check_spends!(node_txn[1], remote_txn[0]);
7411 check_spends!(node_txn[2], remote_txn[0]);
7413 preimage = node_txn[0].txid();
7414 let index = node_txn[0].input[0].previous_output.vout;
7415 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7416 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7418 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7419 (node_txn[2].clone(), node_txn[1].clone())
7421 (node_txn[1].clone(), node_txn[2].clone())
7424 preimage_bump = preimage_bump_tx;
7425 check_spends!(preimage_bump, remote_txn[0]);
7426 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7428 timeout = timeout_tx.txid();
7429 let index = timeout_tx.input[0].previous_output.vout;
7430 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7431 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7435 assert_ne!(feerate_timeout, 0);
7436 assert_ne!(feerate_preimage, 0);
7438 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7439 connect_blocks(&nodes[1], 15);
7441 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7442 assert_eq!(node_txn.len(), 1);
7443 assert_eq!(node_txn[0].input.len(), 1);
7444 assert_eq!(preimage_bump.input.len(), 1);
7445 check_spends!(node_txn[0], remote_txn[0]);
7446 check_spends!(preimage_bump, remote_txn[0]);
7448 let index = preimage_bump.input[0].previous_output.vout;
7449 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7450 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7451 assert!(new_feerate * 100 > feerate_timeout * 125);
7452 assert_ne!(timeout, preimage_bump.txid());
7454 let index = node_txn[0].input[0].previous_output.vout;
7455 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7456 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7457 assert!(new_feerate * 100 > feerate_preimage * 125);
7458 assert_ne!(preimage, node_txn[0].txid());
7463 nodes[1].node.get_and_clear_pending_events();
7464 nodes[1].node.get_and_clear_pending_msg_events();
7468 fn test_counterparty_raa_skip_no_crash() {
7469 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7470 // commitment transaction, we would have happily carried on and provided them the next
7471 // commitment transaction based on one RAA forward. This would probably eventually have led to
7472 // channel closure, but it would not have resulted in funds loss. Still, our
7473 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7474 // check simply that the channel is closed in response to such an RAA, but don't check whether
7475 // we decide to punish our counterparty for revoking their funds (as we don't currently
7477 let chanmon_cfgs = create_chanmon_cfgs(2);
7478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7480 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7481 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7483 let per_commitment_secret;
7484 let next_per_commitment_point;
7486 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7487 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7488 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7490 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7492 // Make signer believe we got a counterparty signature, so that it allows the revocation
7493 keys.get_enforcement_state().last_holder_commitment -= 1;
7494 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7496 // Must revoke without gaps
7497 keys.get_enforcement_state().last_holder_commitment -= 1;
7498 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7500 keys.get_enforcement_state().last_holder_commitment -= 1;
7501 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7502 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7505 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7506 &msgs::RevokeAndACK {
7508 per_commitment_secret,
7509 next_per_commitment_point,
7511 next_local_nonce: None,
7513 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7514 check_added_monitors!(nodes[1], 1);
7515 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7519 fn test_bump_txn_sanitize_tracking_maps() {
7520 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7521 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7523 let chanmon_cfgs = create_chanmon_cfgs(2);
7524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7528 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7529 // Lock HTLC in both directions
7530 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7531 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7533 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7534 assert_eq!(revoked_local_txn[0].input.len(), 1);
7535 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7537 // Revoke local commitment tx
7538 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7540 // Broadcast set of revoked txn on A
7541 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7542 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7543 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7545 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7546 check_closed_broadcast!(nodes[0], true);
7547 check_added_monitors!(nodes[0], 1);
7548 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7550 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7551 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7552 check_spends!(node_txn[0], revoked_local_txn[0]);
7553 check_spends!(node_txn[1], revoked_local_txn[0]);
7554 check_spends!(node_txn[2], revoked_local_txn[0]);
7555 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7559 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7560 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7561 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7563 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7564 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7565 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7570 fn test_pending_claimed_htlc_no_balance_underflow() {
7571 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7572 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7573 let chanmon_cfgs = create_chanmon_cfgs(2);
7574 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7575 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7576 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7577 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7579 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7580 nodes[1].node.claim_funds(payment_preimage);
7581 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7582 check_added_monitors!(nodes[1], 1);
7583 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7585 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7586 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7587 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7588 check_added_monitors!(nodes[0], 1);
7589 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7591 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7592 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7593 // can get our balance.
7595 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7596 // the public key of the only hop. This works around ChannelDetails not showing the
7597 // almost-claimed HTLC as available balance.
7598 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7599 route.payment_params = None; // This is all wrong, but unnecessary
7600 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7601 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7602 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7604 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7608 fn test_channel_conf_timeout() {
7609 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7610 // confirm within 2016 blocks, as recommended by BOLT 2.
7611 let chanmon_cfgs = create_chanmon_cfgs(2);
7612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7614 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7616 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7618 // The outbound node should wait forever for confirmation:
7619 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7620 // copied here instead of directly referencing the constant.
7621 connect_blocks(&nodes[0], 2016);
7622 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7624 // The inbound node should fail the channel after exactly 2016 blocks
7625 connect_blocks(&nodes[1], 2015);
7626 check_added_monitors!(nodes[1], 0);
7627 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7629 connect_blocks(&nodes[1], 1);
7630 check_added_monitors!(nodes[1], 1);
7631 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7632 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7633 assert_eq!(close_ev.len(), 1);
7635 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7636 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7637 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7639 _ => panic!("Unexpected event"),
7644 fn test_override_channel_config() {
7645 let chanmon_cfgs = create_chanmon_cfgs(2);
7646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7650 // Node0 initiates a channel to node1 using the override config.
7651 let mut override_config = UserConfig::default();
7652 override_config.channel_handshake_config.our_to_self_delay = 200;
7654 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7656 // Assert the channel created by node0 is using the override config.
7657 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7658 assert_eq!(res.channel_flags, 0);
7659 assert_eq!(res.to_self_delay, 200);
7663 fn test_override_0msat_htlc_minimum() {
7664 let mut zero_config = UserConfig::default();
7665 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7666 let chanmon_cfgs = create_chanmon_cfgs(2);
7667 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7668 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7669 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7671 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7672 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7673 assert_eq!(res.htlc_minimum_msat, 1);
7675 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7676 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7677 assert_eq!(res.htlc_minimum_msat, 1);
7681 fn test_channel_update_has_correct_htlc_maximum_msat() {
7682 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7683 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7684 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7685 // 90% of the `channel_value`.
7686 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7688 let mut config_30_percent = UserConfig::default();
7689 config_30_percent.channel_handshake_config.announced_channel = true;
7690 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7691 let mut config_50_percent = UserConfig::default();
7692 config_50_percent.channel_handshake_config.announced_channel = true;
7693 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7694 let mut config_95_percent = UserConfig::default();
7695 config_95_percent.channel_handshake_config.announced_channel = true;
7696 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7697 let mut config_100_percent = UserConfig::default();
7698 config_100_percent.channel_handshake_config.announced_channel = true;
7699 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7701 let chanmon_cfgs = create_chanmon_cfgs(4);
7702 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7703 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)]);
7704 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7706 let channel_value_satoshis = 100000;
7707 let channel_value_msat = channel_value_satoshis * 1000;
7708 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7709 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7710 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7712 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7713 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7715 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7716 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7717 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7718 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7719 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7720 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7722 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7723 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7725 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7726 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7727 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7729 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7733 fn test_manually_accept_inbound_channel_request() {
7734 let mut manually_accept_conf = UserConfig::default();
7735 manually_accept_conf.manually_accept_inbound_channels = true;
7736 let chanmon_cfgs = create_chanmon_cfgs(2);
7737 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7738 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7739 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7741 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7742 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7744 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7746 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7747 // accepting the inbound channel request.
7748 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7750 let events = nodes[1].node.get_and_clear_pending_events();
7752 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7753 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7755 _ => panic!("Unexpected event"),
7758 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7759 assert_eq!(accept_msg_ev.len(), 1);
7761 match accept_msg_ev[0] {
7762 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7763 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7765 _ => panic!("Unexpected event"),
7768 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7770 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7771 assert_eq!(close_msg_ev.len(), 1);
7773 let events = nodes[1].node.get_and_clear_pending_events();
7775 Event::ChannelClosed { user_channel_id, .. } => {
7776 assert_eq!(user_channel_id, 23);
7778 _ => panic!("Unexpected event"),
7783 fn test_manually_reject_inbound_channel_request() {
7784 let mut manually_accept_conf = UserConfig::default();
7785 manually_accept_conf.manually_accept_inbound_channels = true;
7786 let chanmon_cfgs = create_chanmon_cfgs(2);
7787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7789 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7791 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7792 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7794 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7796 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7797 // rejecting the inbound channel request.
7798 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7800 let events = nodes[1].node.get_and_clear_pending_events();
7802 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7803 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7805 _ => panic!("Unexpected event"),
7808 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7809 assert_eq!(close_msg_ev.len(), 1);
7811 match close_msg_ev[0] {
7812 MessageSendEvent::HandleError { ref node_id, .. } => {
7813 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7815 _ => panic!("Unexpected event"),
7817 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7821 fn test_reject_funding_before_inbound_channel_accepted() {
7822 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7823 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7824 // the node operator before the counterparty sends a `FundingCreated` message. If a
7825 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7826 // and the channel should be closed.
7827 let mut manually_accept_conf = UserConfig::default();
7828 manually_accept_conf.manually_accept_inbound_channels = true;
7829 let chanmon_cfgs = create_chanmon_cfgs(2);
7830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7834 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7835 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7836 let temp_channel_id = res.temporary_channel_id;
7838 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7840 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7841 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7843 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7844 nodes[1].node.get_and_clear_pending_events();
7846 // Get the `AcceptChannel` message of `nodes[1]` without calling
7847 // `ChannelManager::accept_inbound_channel`, which generates a
7848 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7849 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7850 // succeed when `nodes[0]` is passed to it.
7851 let accept_chan_msg = {
7852 let mut node_1_per_peer_lock;
7853 let mut node_1_peer_state_lock;
7854 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7855 channel.get_accept_channel_message()
7857 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7859 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7861 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7862 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7864 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7865 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7867 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7868 assert_eq!(close_msg_ev.len(), 1);
7870 let expected_err = "FundingCreated message received before the channel was accepted";
7871 match close_msg_ev[0] {
7872 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7873 assert_eq!(msg.channel_id, temp_channel_id);
7874 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7875 assert_eq!(msg.data, expected_err);
7877 _ => panic!("Unexpected event"),
7880 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7884 fn test_can_not_accept_inbound_channel_twice() {
7885 let mut manually_accept_conf = UserConfig::default();
7886 manually_accept_conf.manually_accept_inbound_channels = true;
7887 let chanmon_cfgs = create_chanmon_cfgs(2);
7888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7890 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7892 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7893 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7895 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7897 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7898 // accepting the inbound channel request.
7899 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7901 let events = nodes[1].node.get_and_clear_pending_events();
7903 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7904 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7905 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7907 Err(APIError::APIMisuseError { err }) => {
7908 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7910 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7911 Err(_) => panic!("Unexpected Error"),
7914 _ => panic!("Unexpected event"),
7917 // Ensure that the channel wasn't closed after attempting to accept it twice.
7918 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7919 assert_eq!(accept_msg_ev.len(), 1);
7921 match accept_msg_ev[0] {
7922 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7923 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7925 _ => panic!("Unexpected event"),
7930 fn test_can_not_accept_unknown_inbound_channel() {
7931 let chanmon_cfg = create_chanmon_cfgs(2);
7932 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7933 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7934 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7936 let unknown_channel_id = [0; 32];
7937 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7939 Err(APIError::ChannelUnavailable { err }) => {
7940 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()));
7942 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7943 Err(_) => panic!("Unexpected Error"),
7948 fn test_onion_value_mpp_set_calculation() {
7949 // Test that we use the onion value `amt_to_forward` when
7950 // calculating whether we've reached the `total_msat` of an MPP
7951 // by having a routing node forward more than `amt_to_forward`
7952 // and checking that the receiving node doesn't generate
7953 // a PaymentClaimable event too early
7955 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7956 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7957 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7958 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7960 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7961 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7962 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7963 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7965 let total_msat = 100_000;
7966 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7967 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7968 let sample_path = route.paths.pop().unwrap();
7970 let mut path_1 = sample_path.clone();
7971 path_1[0].pubkey = nodes[1].node.get_our_node_id();
7972 path_1[0].short_channel_id = chan_1_id;
7973 path_1[1].pubkey = nodes[3].node.get_our_node_id();
7974 path_1[1].short_channel_id = chan_3_id;
7975 path_1[1].fee_msat = 100_000;
7976 route.paths.push(path_1);
7978 let mut path_2 = sample_path.clone();
7979 path_2[0].pubkey = nodes[2].node.get_our_node_id();
7980 path_2[0].short_channel_id = chan_2_id;
7981 path_2[1].pubkey = nodes[3].node.get_our_node_id();
7982 path_2[1].short_channel_id = chan_4_id;
7983 path_2[1].fee_msat = 1_000;
7984 route.paths.push(path_2);
7987 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7988 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
7989 nodes[0].node.test_send_payment_internal(&route, our_payment_hash, &Some(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7990 check_added_monitors!(nodes[0], expected_paths.len());
7992 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7993 assert_eq!(events.len(), expected_paths.len());
7996 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
7997 let mut payment_event = SendEvent::from_event(ev);
7998 let mut prev_node = &nodes[0];
8000 for (idx, &node) in expected_paths[0].iter().enumerate() {
8001 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8003 if idx == 0 { // routing node
8004 let session_priv = [3; 32];
8005 let height = nodes[0].best_block_info().1;
8006 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8007 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8008 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000, &Some(our_payment_secret), height + 1, &None).unwrap();
8009 // Edit amt_to_forward to simulate the sender having set
8010 // the final amount and the routing node taking less fee
8011 onion_payloads[1].amt_to_forward = 99_000;
8012 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8013 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8016 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8017 check_added_monitors!(node, 0);
8018 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8019 expect_pending_htlcs_forwardable!(node);
8022 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8023 assert_eq!(events_2.len(), 1);
8024 check_added_monitors!(node, 1);
8025 payment_event = SendEvent::from_event(events_2.remove(0));
8026 assert_eq!(payment_event.msgs.len(), 1);
8028 let events_2 = node.node.get_and_clear_pending_events();
8029 assert!(events_2.is_empty());
8036 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8037 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8039 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8042 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8044 let routing_node_count = msat_amounts.len();
8045 let node_count = routing_node_count + 2;
8047 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8048 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8049 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8050 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8055 // Create channels for each amount
8056 let mut expected_paths = Vec::with_capacity(routing_node_count);
8057 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8058 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8059 for i in 0..routing_node_count {
8060 let routing_node = 2 + i;
8061 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8062 src_chan_ids.push(src_chan_id);
8063 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8064 dst_chan_ids.push(dst_chan_id);
8065 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8066 expected_paths.push(path);
8068 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8070 // Create a route for each amount
8071 let example_amount = 100000;
8072 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);
8073 let sample_path = route.paths.pop().unwrap();
8074 for i in 0..routing_node_count {
8075 let routing_node = 2 + i;
8076 let mut path = sample_path.clone();
8077 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8078 path[0].short_channel_id = src_chan_ids[i];
8079 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8080 path[1].short_channel_id = dst_chan_ids[i];
8081 path[1].fee_msat = msat_amounts[i];
8082 route.paths.push(path);
8085 // Send payment with manually set total_msat
8086 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8087 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
8088 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash, &Some(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8089 check_added_monitors!(nodes[src_idx], expected_paths.len());
8091 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8092 assert_eq!(events.len(), expected_paths.len());
8093 let mut amount_received = 0;
8094 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8095 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8097 let current_path_amount = msat_amounts[path_idx];
8098 amount_received += current_path_amount;
8099 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8100 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8103 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8107 fn test_overshoot_mpp() {
8108 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8109 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8113 fn test_simple_mpp() {
8114 // Simple test of sending a multi-path payment.
8115 let chanmon_cfgs = create_chanmon_cfgs(4);
8116 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8117 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8118 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8120 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8121 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8122 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8123 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8125 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8126 let path = route.paths[0].clone();
8127 route.paths.push(path);
8128 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8129 route.paths[0][0].short_channel_id = chan_1_id;
8130 route.paths[0][1].short_channel_id = chan_3_id;
8131 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8132 route.paths[1][0].short_channel_id = chan_2_id;
8133 route.paths[1][1].short_channel_id = chan_4_id;
8134 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8135 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8139 fn test_preimage_storage() {
8140 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8141 let chanmon_cfgs = create_chanmon_cfgs(2);
8142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8144 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8146 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8149 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8150 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8151 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8152 check_added_monitors!(nodes[0], 1);
8153 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8154 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8155 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8156 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8158 // Note that after leaving the above scope we have no knowledge of any arguments or return
8159 // values from previous calls.
8160 expect_pending_htlcs_forwardable!(nodes[1]);
8161 let events = nodes[1].node.get_and_clear_pending_events();
8162 assert_eq!(events.len(), 1);
8164 Event::PaymentClaimable { ref purpose, .. } => {
8166 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8167 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8169 _ => panic!("expected PaymentPurpose::InvoicePayment")
8172 _ => panic!("Unexpected event"),
8177 #[allow(deprecated)]
8178 fn test_secret_timeout() {
8179 // Simple test of payment secret storage time outs. After
8180 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8181 let chanmon_cfgs = create_chanmon_cfgs(2);
8182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8186 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8188 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8190 // We should fail to register the same payment hash twice, at least until we've connected a
8191 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8192 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8193 assert_eq!(err, "Duplicate payment hash");
8194 } else { panic!(); }
8196 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8198 header: BlockHeader {
8200 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8201 merkle_root: TxMerkleNode::all_zeros(),
8202 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8206 connect_block(&nodes[1], &block);
8207 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8208 assert_eq!(err, "Duplicate payment hash");
8209 } else { panic!(); }
8211 // If we then connect the second block, we should be able to register the same payment hash
8212 // again (this time getting a new payment secret).
8213 block.header.prev_blockhash = block.header.block_hash();
8214 block.header.time += 1;
8215 connect_block(&nodes[1], &block);
8216 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8217 assert_ne!(payment_secret_1, our_payment_secret);
8220 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8221 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8222 check_added_monitors!(nodes[0], 1);
8223 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8224 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8225 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8226 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8228 // Note that after leaving the above scope we have no knowledge of any arguments or return
8229 // values from previous calls.
8230 expect_pending_htlcs_forwardable!(nodes[1]);
8231 let events = nodes[1].node.get_and_clear_pending_events();
8232 assert_eq!(events.len(), 1);
8234 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8235 assert!(payment_preimage.is_none());
8236 assert_eq!(payment_secret, our_payment_secret);
8237 // We don't actually have the payment preimage with which to claim this payment!
8239 _ => panic!("Unexpected event"),
8244 fn test_bad_secret_hash() {
8245 // Simple test of unregistered payment hash/invalid payment secret handling
8246 let chanmon_cfgs = create_chanmon_cfgs(2);
8247 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8248 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8249 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8251 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8253 let random_payment_hash = PaymentHash([42; 32]);
8254 let random_payment_secret = PaymentSecret([43; 32]);
8255 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8256 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8258 // All the below cases should end up being handled exactly identically, so we macro the
8259 // resulting events.
8260 macro_rules! handle_unknown_invalid_payment_data {
8261 ($payment_hash: expr) => {
8262 check_added_monitors!(nodes[0], 1);
8263 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8264 let payment_event = SendEvent::from_event(events.pop().unwrap());
8265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8266 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8268 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8269 // again to process the pending backwards-failure of the HTLC
8270 expect_pending_htlcs_forwardable!(nodes[1]);
8271 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8272 check_added_monitors!(nodes[1], 1);
8274 // We should fail the payment back
8275 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8276 match events.pop().unwrap() {
8277 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8278 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8279 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8281 _ => panic!("Unexpected event"),
8286 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8287 // Error data is the HTLC value (100,000) and current block height
8288 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8290 // Send a payment with the right payment hash but the wrong payment secret
8291 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8292 handle_unknown_invalid_payment_data!(our_payment_hash);
8293 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8295 // Send a payment with a random payment hash, but the right payment secret
8296 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8297 handle_unknown_invalid_payment_data!(random_payment_hash);
8298 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8300 // Send a payment with a random payment hash and random payment secret
8301 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8302 handle_unknown_invalid_payment_data!(random_payment_hash);
8303 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8307 fn test_update_err_monitor_lockdown() {
8308 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8309 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8310 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8313 // This scenario may happen in a watchtower setup, where watchtower process a block height
8314 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8315 // commitment at same time.
8317 let chanmon_cfgs = create_chanmon_cfgs(2);
8318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8320 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8322 // Create some initial channel
8323 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8324 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8326 // Rebalance the network to generate htlc in the two directions
8327 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8329 // Route a HTLC from node 0 to node 1 (but don't settle)
8330 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8332 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8333 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8334 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8335 let persister = test_utils::TestPersister::new();
8338 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8339 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8340 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8341 assert!(new_monitor == *monitor);
8344 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);
8345 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8348 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8349 let block = Block { header, txdata: vec![] };
8350 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8351 // transaction lock time requirements here.
8352 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8353 watchtower.chain_monitor.block_connected(&block, 200);
8355 // Try to update ChannelMonitor
8356 nodes[1].node.claim_funds(preimage);
8357 check_added_monitors!(nodes[1], 1);
8358 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8360 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8361 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8362 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8364 let mut node_0_per_peer_lock;
8365 let mut node_0_peer_state_lock;
8366 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8367 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8368 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8369 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8370 } else { assert!(false); }
8372 // Our local monitor is in-sync and hasn't processed yet timeout
8373 check_added_monitors!(nodes[0], 1);
8374 let events = nodes[0].node.get_and_clear_pending_events();
8375 assert_eq!(events.len(), 1);
8379 fn test_concurrent_monitor_claim() {
8380 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8381 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8382 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8383 // state N+1 confirms. Alice claims output from state N+1.
8385 let chanmon_cfgs = create_chanmon_cfgs(2);
8386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8390 // Create some initial channel
8391 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8392 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8394 // Rebalance the network to generate htlc in the two directions
8395 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8397 // Route a HTLC from node 0 to node 1 (but don't settle)
8398 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8400 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8401 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8402 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8403 let persister = test_utils::TestPersister::new();
8404 let watchtower_alice = {
8406 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8407 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8408 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8409 assert!(new_monitor == *monitor);
8412 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8413 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8416 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8417 let block = Block { header, txdata: vec![] };
8418 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8419 // transaction lock time requirements here.
8420 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (block.clone(), 0));
8421 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8423 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8425 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8426 assert_eq!(txn.len(), 2);
8430 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8431 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8432 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8433 let persister = test_utils::TestPersister::new();
8434 let watchtower_bob = {
8436 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8437 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8438 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8439 assert!(new_monitor == *monitor);
8442 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);
8443 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8446 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8447 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8449 // Route another payment to generate another update with still previous HTLC pending
8450 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8452 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8454 check_added_monitors!(nodes[1], 1);
8456 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8457 assert_eq!(updates.update_add_htlcs.len(), 1);
8458 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8460 let mut node_0_per_peer_lock;
8461 let mut node_0_peer_state_lock;
8462 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8463 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8464 // Watchtower Alice should already have seen the block and reject the update
8465 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8466 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8467 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8468 } else { assert!(false); }
8470 // Our local monitor is in-sync and hasn't processed yet timeout
8471 check_added_monitors!(nodes[0], 1);
8473 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8474 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8475 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8477 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8480 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8481 assert_eq!(txn.len(), 2);
8482 bob_state_y = txn[0].clone();
8486 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8487 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8488 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![bob_state_y.clone()] }, CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8490 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8491 assert_eq!(htlc_txn.len(), 1);
8492 check_spends!(htlc_txn[0], bob_state_y);
8497 fn test_pre_lockin_no_chan_closed_update() {
8498 // Test that if a peer closes a channel in response to a funding_created message we don't
8499 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8502 // Doing so would imply a channel monitor update before the initial channel monitor
8503 // registration, violating our API guarantees.
8505 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8506 // then opening a second channel with the same funding output as the first (which is not
8507 // rejected because the first channel does not exist in the ChannelManager) and closing it
8508 // before receiving funding_signed.
8509 let chanmon_cfgs = create_chanmon_cfgs(2);
8510 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8511 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8512 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8514 // Create an initial channel
8515 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8516 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8517 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8518 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8519 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8521 // Move the first channel through the funding flow...
8522 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8524 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8525 check_added_monitors!(nodes[0], 0);
8527 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8528 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8529 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8530 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8531 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8535 fn test_htlc_no_detection() {
8536 // This test is a mutation to underscore the detection logic bug we had
8537 // before #653. HTLC value routed is above the remaining balance, thus
8538 // inverting HTLC and `to_remote` output. HTLC will come second and
8539 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8540 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8541 // outputs order detection for correct spending children filtring.
8543 let chanmon_cfgs = create_chanmon_cfgs(2);
8544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8546 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8548 // Create some initial channels
8549 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8551 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8552 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8553 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8554 assert_eq!(local_txn[0].input.len(), 1);
8555 assert_eq!(local_txn[0].output.len(), 3);
8556 check_spends!(local_txn[0], chan_1.3);
8558 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8559 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8560 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8561 // We deliberately connect the local tx twice as this should provoke a failure calling
8562 // this test before #653 fix.
8563 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8564 check_closed_broadcast!(nodes[0], true);
8565 check_added_monitors!(nodes[0], 1);
8566 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8567 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8569 let htlc_timeout = {
8570 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8571 assert_eq!(node_txn.len(), 1);
8572 assert_eq!(node_txn[0].input.len(), 1);
8573 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8574 check_spends!(node_txn[0], local_txn[0]);
8578 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8579 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8580 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8581 expect_payment_failed!(nodes[0], our_payment_hash, false);
8584 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8585 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8586 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8587 // Carol, Alice would be the upstream node, and Carol the downstream.)
8589 // Steps of the test:
8590 // 1) Alice sends a HTLC to Carol through Bob.
8591 // 2) Carol doesn't settle the HTLC.
8592 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8593 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8594 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8595 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8596 // 5) Carol release the preimage to Bob off-chain.
8597 // 6) Bob claims the offered output on the broadcasted commitment.
8598 let chanmon_cfgs = create_chanmon_cfgs(3);
8599 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8600 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8601 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8603 // Create some initial channels
8604 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8605 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8607 // Steps (1) and (2):
8608 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8609 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8611 // Check that Alice's commitment transaction now contains an output for this HTLC.
8612 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8613 check_spends!(alice_txn[0], chan_ab.3);
8614 assert_eq!(alice_txn[0].output.len(), 2);
8615 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8616 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8617 assert_eq!(alice_txn.len(), 2);
8619 // Steps (3) and (4):
8620 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8621 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8622 let mut force_closing_node = 0; // Alice force-closes
8623 let mut counterparty_node = 1; // Bob if Alice force-closes
8626 if !broadcast_alice {
8627 force_closing_node = 1;
8628 counterparty_node = 0;
8630 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8631 check_closed_broadcast!(nodes[force_closing_node], true);
8632 check_added_monitors!(nodes[force_closing_node], 1);
8633 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8634 if go_onchain_before_fulfill {
8635 let txn_to_broadcast = match broadcast_alice {
8636 true => alice_txn.clone(),
8637 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8639 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8640 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8641 if broadcast_alice {
8642 check_closed_broadcast!(nodes[1], true);
8643 check_added_monitors!(nodes[1], 1);
8644 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8649 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8650 // process of removing the HTLC from their commitment transactions.
8651 nodes[2].node.claim_funds(payment_preimage);
8652 check_added_monitors!(nodes[2], 1);
8653 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8655 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8656 assert!(carol_updates.update_add_htlcs.is_empty());
8657 assert!(carol_updates.update_fail_htlcs.is_empty());
8658 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8659 assert!(carol_updates.update_fee.is_none());
8660 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8662 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8663 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8664 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8665 if !go_onchain_before_fulfill && broadcast_alice {
8666 let events = nodes[1].node.get_and_clear_pending_msg_events();
8667 assert_eq!(events.len(), 1);
8669 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8670 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8672 _ => panic!("Unexpected event"),
8675 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8676 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8677 // Carol<->Bob's updated commitment transaction info.
8678 check_added_monitors!(nodes[1], 2);
8680 let events = nodes[1].node.get_and_clear_pending_msg_events();
8681 assert_eq!(events.len(), 2);
8682 let bob_revocation = match events[0] {
8683 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8684 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8687 _ => panic!("Unexpected event"),
8689 let bob_updates = match events[1] {
8690 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8691 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8694 _ => panic!("Unexpected event"),
8697 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8698 check_added_monitors!(nodes[2], 1);
8699 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8700 check_added_monitors!(nodes[2], 1);
8702 let events = nodes[2].node.get_and_clear_pending_msg_events();
8703 assert_eq!(events.len(), 1);
8704 let carol_revocation = match events[0] {
8705 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8706 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8709 _ => panic!("Unexpected event"),
8711 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8712 check_added_monitors!(nodes[1], 1);
8714 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8715 // here's where we put said channel's commitment tx on-chain.
8716 let mut txn_to_broadcast = alice_txn.clone();
8717 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8718 if !go_onchain_before_fulfill {
8719 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8720 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8721 // If Bob was the one to force-close, he will have already passed these checks earlier.
8722 if broadcast_alice {
8723 check_closed_broadcast!(nodes[1], true);
8724 check_added_monitors!(nodes[1], 1);
8725 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8727 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8728 if broadcast_alice {
8729 assert_eq!(bob_txn.len(), 1);
8730 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8732 assert_eq!(bob_txn.len(), 2);
8733 check_spends!(bob_txn[0], chan_ab.3);
8738 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8739 // broadcasted commitment transaction.
8741 let script_weight = match broadcast_alice {
8742 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8743 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8745 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8746 // Bob force-closed and broadcasts the commitment transaction along with a
8747 // HTLC-output-claiming transaction.
8748 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8749 if broadcast_alice {
8750 assert_eq!(bob_txn.len(), 1);
8751 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8752 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8754 assert_eq!(bob_txn.len(), 2);
8755 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8756 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8762 fn test_onchain_htlc_settlement_after_close() {
8763 do_test_onchain_htlc_settlement_after_close(true, true);
8764 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8765 do_test_onchain_htlc_settlement_after_close(true, false);
8766 do_test_onchain_htlc_settlement_after_close(false, false);
8770 fn test_duplicate_temporary_channel_id_from_different_peers() {
8771 // Tests that we can accept two different `OpenChannel` requests with the same
8772 // `temporary_channel_id`, as long as they are from different peers.
8773 let chanmon_cfgs = create_chanmon_cfgs(3);
8774 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8775 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8776 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8778 // Create an first channel channel
8779 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8780 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8782 // Create an second channel
8783 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8784 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8786 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8787 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8788 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8790 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8791 // `temporary_channel_id` as they are from different peers.
8792 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8794 let events = nodes[0].node.get_and_clear_pending_msg_events();
8795 assert_eq!(events.len(), 1);
8797 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8798 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8799 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8801 _ => panic!("Unexpected event"),
8805 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8807 let events = nodes[0].node.get_and_clear_pending_msg_events();
8808 assert_eq!(events.len(), 1);
8810 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8811 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8812 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8814 _ => panic!("Unexpected event"),
8820 fn test_duplicate_chan_id() {
8821 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8822 // already open we reject it and keep the old channel.
8824 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8825 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8826 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8827 // updating logic for the existing channel.
8828 let chanmon_cfgs = create_chanmon_cfgs(2);
8829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8830 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8831 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8833 // Create an initial channel
8834 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8835 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8836 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8837 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()));
8839 // Try to create a second channel with the same temporary_channel_id as the first and check
8840 // that it is rejected.
8841 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8843 let events = nodes[1].node.get_and_clear_pending_msg_events();
8844 assert_eq!(events.len(), 1);
8846 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8847 // Technically, at this point, nodes[1] would be justified in thinking both the
8848 // first (valid) and second (invalid) channels are closed, given they both have
8849 // the same non-temporary channel_id. However, currently we do not, so we just
8850 // move forward with it.
8851 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8852 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8854 _ => panic!("Unexpected event"),
8858 // Move the first channel through the funding flow...
8859 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8861 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8862 check_added_monitors!(nodes[0], 0);
8864 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8865 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8867 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8868 assert_eq!(added_monitors.len(), 1);
8869 assert_eq!(added_monitors[0].0, funding_output);
8870 added_monitors.clear();
8872 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8874 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8876 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8877 let channel_id = funding_outpoint.to_channel_id();
8879 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8882 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8883 // Technically this is allowed by the spec, but we don't support it and there's little reason
8884 // to. Still, it shouldn't cause any other issues.
8885 open_chan_msg.temporary_channel_id = channel_id;
8886 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8888 let events = nodes[1].node.get_and_clear_pending_msg_events();
8889 assert_eq!(events.len(), 1);
8891 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8892 // Technically, at this point, nodes[1] would be justified in thinking both
8893 // channels are closed, but currently we do not, so we just move forward with it.
8894 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8895 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8897 _ => panic!("Unexpected event"),
8901 // Now try to create a second channel which has a duplicate funding output.
8902 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8903 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8904 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8905 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()));
8906 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8908 let funding_created = {
8909 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8910 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8911 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8912 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8913 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8914 // channelmanager in a possibly nonsense state instead).
8915 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8916 let logger = test_utils::TestLogger::new();
8917 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8919 check_added_monitors!(nodes[0], 0);
8920 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8921 // At this point we'll look up if the channel_id is present and immediately fail the channel
8922 // without trying to persist the `ChannelMonitor`.
8923 check_added_monitors!(nodes[1], 0);
8925 // ...still, nodes[1] will reject the duplicate channel.
8927 let events = nodes[1].node.get_and_clear_pending_msg_events();
8928 assert_eq!(events.len(), 1);
8930 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8931 // Technically, at this point, nodes[1] would be justified in thinking both
8932 // channels are closed, but currently we do not, so we just move forward with it.
8933 assert_eq!(msg.channel_id, channel_id);
8934 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8936 _ => panic!("Unexpected event"),
8940 // finally, finish creating the original channel and send a payment over it to make sure
8941 // everything is functional.
8942 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8944 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8945 assert_eq!(added_monitors.len(), 1);
8946 assert_eq!(added_monitors[0].0, funding_output);
8947 added_monitors.clear();
8949 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8951 let events_4 = nodes[0].node.get_and_clear_pending_events();
8952 assert_eq!(events_4.len(), 0);
8953 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8954 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8956 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8957 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8958 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8960 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8964 fn test_error_chans_closed() {
8965 // Test that we properly handle error messages, closing appropriate channels.
8967 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8968 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8969 // we can test various edge cases around it to ensure we don't regress.
8970 let chanmon_cfgs = create_chanmon_cfgs(3);
8971 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8972 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8973 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8975 // Create some initial channels
8976 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8977 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8978 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8980 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8981 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8982 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8984 // Closing a channel from a different peer has no effect
8985 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8986 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8988 // Closing one channel doesn't impact others
8989 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8990 check_added_monitors!(nodes[0], 1);
8991 check_closed_broadcast!(nodes[0], false);
8992 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8993 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8994 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8995 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);
8996 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);
8998 // A null channel ID should close all channels
8999 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9000 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9001 check_added_monitors!(nodes[0], 2);
9002 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9003 let events = nodes[0].node.get_and_clear_pending_msg_events();
9004 assert_eq!(events.len(), 2);
9006 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9007 assert_eq!(msg.contents.flags & 2, 2);
9009 _ => panic!("Unexpected event"),
9012 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9013 assert_eq!(msg.contents.flags & 2, 2);
9015 _ => panic!("Unexpected event"),
9017 // Note that at this point users of a standard PeerHandler will end up calling
9018 // peer_disconnected.
9019 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9020 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9022 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9023 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9024 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9028 fn test_invalid_funding_tx() {
9029 // Test that we properly handle invalid funding transactions sent to us from a peer.
9031 // Previously, all other major lightning implementations had failed to properly sanitize
9032 // funding transactions from their counterparties, leading to a multi-implementation critical
9033 // security vulnerability (though we always sanitized properly, we've previously had
9034 // un-released crashes in the sanitization process).
9036 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9037 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9038 // gave up on it. We test this here by generating such a transaction.
9039 let chanmon_cfgs = create_chanmon_cfgs(2);
9040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9042 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9044 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9045 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()));
9046 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()));
9048 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9050 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9051 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9052 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9054 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9055 let wit_program_script: Script = wit_program.into();
9056 for output in tx.output.iter_mut() {
9057 // Make the confirmed funding transaction have a bogus script_pubkey
9058 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9061 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9062 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()));
9063 check_added_monitors!(nodes[1], 1);
9064 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9066 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()));
9067 check_added_monitors!(nodes[0], 1);
9068 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9070 let events_1 = nodes[0].node.get_and_clear_pending_events();
9071 assert_eq!(events_1.len(), 0);
9073 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9074 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9075 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9077 let expected_err = "funding tx had wrong script/value or output index";
9078 confirm_transaction_at(&nodes[1], &tx, 1);
9079 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9080 check_added_monitors!(nodes[1], 1);
9081 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9082 assert_eq!(events_2.len(), 1);
9083 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9084 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9085 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9086 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9087 } else { panic!(); }
9088 } else { panic!(); }
9089 assert_eq!(nodes[1].node.list_channels().len(), 0);
9091 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9092 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9093 // as its not 32 bytes long.
9094 let mut spend_tx = Transaction {
9095 version: 2i32, lock_time: PackedLockTime::ZERO,
9096 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9097 previous_output: BitcoinOutPoint {
9101 script_sig: Script::new(),
9102 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9103 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9105 output: vec![TxOut {
9107 script_pubkey: Script::new(),
9110 check_spends!(spend_tx, tx);
9111 mine_transaction(&nodes[1], &spend_tx);
9114 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9115 // In the first version of the chain::Confirm interface, after a refactor was made to not
9116 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9117 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9118 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9119 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9120 // spending transaction until height N+1 (or greater). This was due to the way
9121 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9122 // spending transaction at the height the input transaction was confirmed at, not whether we
9123 // should broadcast a spending transaction at the current height.
9124 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9125 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9126 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9127 // until we learned about an additional block.
9129 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9130 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9131 let chanmon_cfgs = create_chanmon_cfgs(3);
9132 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9133 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9134 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9135 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9137 create_announced_chan_between_nodes(&nodes, 0, 1);
9138 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9139 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9140 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9141 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9143 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9144 check_closed_broadcast!(nodes[1], true);
9145 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9146 check_added_monitors!(nodes[1], 1);
9147 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9148 assert_eq!(node_txn.len(), 1);
9150 let conf_height = nodes[1].best_block_info().1;
9151 if !test_height_before_timelock {
9152 connect_blocks(&nodes[1], 24 * 6);
9154 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9155 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9156 if test_height_before_timelock {
9157 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9158 // generate any events or broadcast any transactions
9159 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9160 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9162 // We should broadcast an HTLC transaction spending our funding transaction first
9163 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9164 assert_eq!(spending_txn.len(), 2);
9165 assert_eq!(spending_txn[0], node_txn[0]);
9166 check_spends!(spending_txn[1], node_txn[0]);
9167 // We should also generate a SpendableOutputs event with the to_self output (as its
9169 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9170 assert_eq!(descriptor_spend_txn.len(), 1);
9172 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9173 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9174 // additional block built on top of the current chain.
9175 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9176 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9177 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 }]);
9178 check_added_monitors!(nodes[1], 1);
9180 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9181 assert!(updates.update_add_htlcs.is_empty());
9182 assert!(updates.update_fulfill_htlcs.is_empty());
9183 assert_eq!(updates.update_fail_htlcs.len(), 1);
9184 assert!(updates.update_fail_malformed_htlcs.is_empty());
9185 assert!(updates.update_fee.is_none());
9186 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9187 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9188 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9193 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9194 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9195 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9198 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9199 let chanmon_cfgs = create_chanmon_cfgs(2);
9200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9202 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9204 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9206 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9207 .with_features(nodes[1].node.invoice_features());
9208 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9210 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9213 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9214 check_added_monitors!(nodes[0], 1);
9215 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9216 assert_eq!(events.len(), 1);
9217 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9218 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9219 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9221 expect_pending_htlcs_forwardable!(nodes[1]);
9222 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9225 // Note that we use a different PaymentId here to allow us to duplicativly pay
9226 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9227 check_added_monitors!(nodes[0], 1);
9228 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9229 assert_eq!(events.len(), 1);
9230 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9231 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9232 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9233 // At this point, nodes[1] would notice it has too much value for the payment. It will
9234 // assume the second is a privacy attack (no longer particularly relevant
9235 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9236 // the first HTLC delivered above.
9239 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9240 nodes[1].node.process_pending_htlc_forwards();
9242 if test_for_second_fail_panic {
9243 // Now we go fail back the first HTLC from the user end.
9244 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9246 let expected_destinations = vec![
9247 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9248 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9250 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9251 nodes[1].node.process_pending_htlc_forwards();
9253 check_added_monitors!(nodes[1], 1);
9254 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9255 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9257 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9258 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9259 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9261 let failure_events = nodes[0].node.get_and_clear_pending_events();
9262 assert_eq!(failure_events.len(), 4);
9263 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9264 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9265 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9266 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9268 // Let the second HTLC fail and claim the first
9269 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9270 nodes[1].node.process_pending_htlc_forwards();
9272 check_added_monitors!(nodes[1], 1);
9273 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9274 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9275 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9277 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9279 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9284 fn test_dup_htlc_second_fail_panic() {
9285 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9286 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9287 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9288 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9289 do_test_dup_htlc_second_rejected(true);
9293 fn test_dup_htlc_second_rejected() {
9294 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9295 // simply reject the second HTLC but are still able to claim the first HTLC.
9296 do_test_dup_htlc_second_rejected(false);
9300 fn test_inconsistent_mpp_params() {
9301 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9302 // such HTLC and allow the second to stay.
9303 let chanmon_cfgs = create_chanmon_cfgs(4);
9304 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9305 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9306 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9308 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9309 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9310 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9311 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9313 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9314 .with_features(nodes[3].node.invoice_features());
9315 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9316 assert_eq!(route.paths.len(), 2);
9317 route.paths.sort_by(|path_a, _| {
9318 // Sort the path so that the path through nodes[1] comes first
9319 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9320 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9323 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9325 let cur_height = nodes[0].best_block_info().1;
9326 let payment_id = PaymentId([42; 32]);
9328 let session_privs = {
9329 // We create a fake route here so that we start with three pending HTLCs, which we'll
9330 // ultimately have, just not right away.
9331 let mut dup_route = route.clone();
9332 dup_route.paths.push(route.paths[1].clone());
9333 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9335 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[0]).unwrap();
9336 check_added_monitors!(nodes[0], 1);
9339 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9340 assert_eq!(events.len(), 1);
9341 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9343 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9345 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9346 check_added_monitors!(nodes[0], 1);
9349 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9350 assert_eq!(events.len(), 1);
9351 let payment_event = SendEvent::from_event(events.pop().unwrap());
9353 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9354 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9356 expect_pending_htlcs_forwardable!(nodes[2]);
9357 check_added_monitors!(nodes[2], 1);
9359 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9360 assert_eq!(events.len(), 1);
9361 let payment_event = SendEvent::from_event(events.pop().unwrap());
9363 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9364 check_added_monitors!(nodes[3], 0);
9365 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9367 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9368 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9369 // post-payment_secrets) and fail back the new HTLC.
9371 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9372 nodes[3].node.process_pending_htlc_forwards();
9373 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9374 nodes[3].node.process_pending_htlc_forwards();
9376 check_added_monitors!(nodes[3], 1);
9378 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9379 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9380 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9382 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 }]);
9383 check_added_monitors!(nodes[2], 1);
9385 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9386 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9387 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9389 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9391 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash, &Some(our_payment_secret), 15_000_000, cur_height, payment_id, &None, session_privs[2]).unwrap();
9392 check_added_monitors!(nodes[0], 1);
9394 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9395 assert_eq!(events.len(), 1);
9396 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9398 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9399 let events = nodes[0].node.get_and_clear_pending_events();
9400 assert_eq!(events.len(), 3);
9402 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9403 assert_eq!(payment_hash, our_payment_hash);
9405 _ => panic!("Unexpected event")
9408 Event::PaymentPathSuccessful { payment_hash, .. } => {
9409 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9411 _ => panic!("Unexpected event")
9414 Event::PaymentPathSuccessful { payment_hash, .. } => {
9415 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9417 _ => panic!("Unexpected event")
9422 fn test_keysend_payments_to_public_node() {
9423 let chanmon_cfgs = create_chanmon_cfgs(2);
9424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9426 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9428 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9429 let network_graph = nodes[0].network_graph.clone();
9430 let payer_pubkey = nodes[0].node.get_our_node_id();
9431 let payee_pubkey = nodes[1].node.get_our_node_id();
9432 let route_params = RouteParameters {
9433 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9434 final_value_msat: 10000,
9436 let scorer = test_utils::TestScorer::new();
9437 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9438 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9440 let test_preimage = PaymentPreimage([42; 32]);
9441 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9442 check_added_monitors!(nodes[0], 1);
9443 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9444 assert_eq!(events.len(), 1);
9445 let event = events.pop().unwrap();
9446 let path = vec![&nodes[1]];
9447 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9448 claim_payment(&nodes[0], &path, test_preimage);
9452 fn test_keysend_payments_to_private_node() {
9453 let chanmon_cfgs = create_chanmon_cfgs(2);
9454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9456 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9458 let payer_pubkey = nodes[0].node.get_our_node_id();
9459 let payee_pubkey = nodes[1].node.get_our_node_id();
9461 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9462 let route_params = RouteParameters {
9463 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9464 final_value_msat: 10000,
9466 let network_graph = nodes[0].network_graph.clone();
9467 let first_hops = nodes[0].node.list_usable_channels();
9468 let scorer = test_utils::TestScorer::new();
9469 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9470 let route = find_route(
9471 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9472 nodes[0].logger, &scorer, &random_seed_bytes
9475 let test_preimage = PaymentPreimage([42; 32]);
9476 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9477 check_added_monitors!(nodes[0], 1);
9478 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9479 assert_eq!(events.len(), 1);
9480 let event = events.pop().unwrap();
9481 let path = vec![&nodes[1]];
9482 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9483 claim_payment(&nodes[0], &path, test_preimage);
9487 fn test_double_partial_claim() {
9488 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9489 // time out, the sender resends only some of the MPP parts, then the user processes the
9490 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9492 let chanmon_cfgs = create_chanmon_cfgs(4);
9493 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9494 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9495 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9497 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9498 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9499 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9500 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9502 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9503 assert_eq!(route.paths.len(), 2);
9504 route.paths.sort_by(|path_a, _| {
9505 // Sort the path so that the path through nodes[1] comes first
9506 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9507 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9510 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9511 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9512 // amount of time to respond to.
9514 // Connect some blocks to time out the payment
9515 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9516 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9518 let failed_destinations = vec![
9519 HTLCDestination::FailedPayment { payment_hash },
9520 HTLCDestination::FailedPayment { payment_hash },
9522 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9524 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9526 // nodes[1] now retries one of the two paths...
9527 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9528 check_added_monitors!(nodes[0], 2);
9530 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9531 assert_eq!(events.len(), 2);
9532 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9533 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9535 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9536 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9537 nodes[3].node.claim_funds(payment_preimage);
9538 check_added_monitors!(nodes[3], 0);
9539 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9542 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9543 #[derive(Clone, Copy, PartialEq)]
9544 enum ExposureEvent {
9545 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9547 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9549 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9550 AtUpdateFeeOutbound,
9553 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9554 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9557 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9558 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9559 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9560 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9561 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9562 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9563 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9564 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9566 let chanmon_cfgs = create_chanmon_cfgs(2);
9567 let mut config = test_default_channel_config();
9568 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9573 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9574 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9575 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9576 open_channel.max_accepted_htlcs = 60;
9578 open_channel.dust_limit_satoshis = 546;
9580 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9581 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9582 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9584 let opt_anchors = false;
9586 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9589 let mut node_0_per_peer_lock;
9590 let mut node_0_peer_state_lock;
9591 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9592 chan.holder_dust_limit_satoshis = 546;
9595 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9596 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()));
9597 check_added_monitors!(nodes[1], 1);
9598 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9600 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()));
9601 check_added_monitors!(nodes[0], 1);
9602 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9604 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9605 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9606 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9608 let dust_buffer_feerate = {
9609 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9610 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9611 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9612 chan.get_dust_buffer_feerate(None) as u64
9614 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;
9615 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9617 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;
9618 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9620 let dust_htlc_on_counterparty_tx: u64 = 25;
9621 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9624 if dust_outbound_balance {
9625 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9626 // Outbound dust balance: 4372 sats
9627 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9628 for i in 0..dust_outbound_htlc_on_holder_tx {
9629 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9630 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9633 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9634 // Inbound dust balance: 4372 sats
9635 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9636 for _ in 0..dust_inbound_htlc_on_holder_tx {
9637 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9641 if dust_outbound_balance {
9642 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9643 // Outbound dust balance: 5000 sats
9644 for i in 0..dust_htlc_on_counterparty_tx {
9645 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9646 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at dust HTLC {}", i); }
9649 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9650 // Inbound dust balance: 5000 sats
9651 for _ in 0..dust_htlc_on_counterparty_tx {
9652 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9657 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9658 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9659 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 });
9660 let mut config = UserConfig::default();
9661 // With default dust exposure: 5000 sats
9663 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9664 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9665 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, 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)));
9667 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)), true, APIError::ChannelUnavailable { ref err }, 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)));
9669 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9670 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 });
9671 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9672 check_added_monitors!(nodes[1], 1);
9673 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9674 assert_eq!(events.len(), 1);
9675 let payment_event = SendEvent::from_event(events.remove(0));
9676 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9677 // With default dust exposure: 5000 sats
9679 // Outbound dust balance: 6399 sats
9680 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9681 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9682 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);
9684 // Outbound dust balance: 5200 sats
9685 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);
9687 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9688 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9689 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9691 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9692 *feerate_lock = *feerate_lock * 10;
9694 nodes[0].node.timer_tick_occurred();
9695 check_added_monitors!(nodes[0], 1);
9696 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9699 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9700 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9701 added_monitors.clear();
9705 fn test_max_dust_htlc_exposure() {
9706 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9707 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9708 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9709 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9710 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9711 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9712 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9713 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9714 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9715 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9716 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9717 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9721 fn test_non_final_funding_tx() {
9722 let chanmon_cfgs = create_chanmon_cfgs(2);
9723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9727 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9728 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9729 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9730 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9731 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9733 let best_height = nodes[0].node.best_block.read().unwrap().height();
9735 let chan_id = *nodes[0].network_chan_count.borrow();
9736 let events = nodes[0].node.get_and_clear_pending_events();
9737 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9738 assert_eq!(events.len(), 1);
9739 let mut tx = match events[0] {
9740 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9741 // Timelock the transaction _beyond_ the best client height + 2.
9742 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9743 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9746 _ => panic!("Unexpected event"),
9748 // Transaction should fail as it's evaluated as non-final for propagation.
9749 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9750 Err(APIError::APIMisuseError { err }) => {
9751 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9756 // However, transaction should be accepted if it's in a +2 headroom from best block.
9757 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9758 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9759 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9763 fn accept_busted_but_better_fee() {
9764 // If a peer sends us a fee update that is too low, but higher than our previous channel
9765 // feerate, we should accept it. In the future we may want to consider closing the channel
9766 // later, but for now we only accept the update.
9767 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9768 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9769 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9770 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9772 create_chan_between_nodes(&nodes[0], &nodes[1]);
9774 // Set nodes[1] to expect 5,000 sat/kW.
9776 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9777 *feerate_lock = 5000;
9780 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9782 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9783 *feerate_lock = 1000;
9785 nodes[0].node.timer_tick_occurred();
9786 check_added_monitors!(nodes[0], 1);
9788 let events = nodes[0].node.get_and_clear_pending_msg_events();
9789 assert_eq!(events.len(), 1);
9791 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9792 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9793 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9795 _ => panic!("Unexpected event"),
9798 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9801 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9802 *feerate_lock = 2000;
9804 nodes[0].node.timer_tick_occurred();
9805 check_added_monitors!(nodes[0], 1);
9807 let events = nodes[0].node.get_and_clear_pending_msg_events();
9808 assert_eq!(events.len(), 1);
9810 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9811 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9812 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9814 _ => panic!("Unexpected event"),
9817 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9820 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9821 *feerate_lock = 1000;
9823 nodes[0].node.timer_tick_occurred();
9824 check_added_monitors!(nodes[0], 1);
9826 let events = nodes[0].node.get_and_clear_pending_msg_events();
9827 assert_eq!(events.len(), 1);
9829 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9830 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9831 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9832 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9833 check_closed_broadcast!(nodes[1], true);
9834 check_added_monitors!(nodes[1], 1);
9836 _ => panic!("Unexpected event"),
9840 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9841 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9842 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9843 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9844 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9845 let min_final_cltv_expiry_delta = 120;
9846 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9847 min_final_cltv_expiry_delta - 2 };
9848 let recv_value = 100_000;
9850 create_chan_between_nodes(&nodes[0], &nodes[1]);
9852 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9853 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9854 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9855 Some(recv_value), Some(min_final_cltv_expiry_delta));
9856 (payment_hash, payment_preimage, payment_secret)
9858 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9859 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9861 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9862 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9863 check_added_monitors!(nodes[0], 1);
9864 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9865 assert_eq!(events.len(), 1);
9866 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9867 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9868 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9869 expect_pending_htlcs_forwardable!(nodes[1]);
9872 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9873 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9875 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9877 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9879 check_added_monitors!(nodes[1], 1);
9881 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9882 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9883 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9885 expect_payment_failed!(nodes[0], payment_hash, true);
9890 fn test_payment_with_custom_min_cltv_expiry_delta() {
9891 do_payment_with_custom_min_final_cltv_expiry(false, false);
9892 do_payment_with_custom_min_final_cltv_expiry(false, true);
9893 do_payment_with_custom_min_final_cltv_expiry(true, false);
9894 do_payment_with_custom_min_final_cltv_expiry(true, true);