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
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
797 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
798 assert_eq!(added_monitors.len(), 0);
799 added_monitors.clear();
801 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
802 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
803 // node[1] has nothing to do
805 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
806 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
807 check_added_monitors!(nodes[0], 1);
809 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
810 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
811 // No commitment_signed so get_event_msg's assert(len == 1) passes
812 check_added_monitors!(nodes[0], 1);
813 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
814 check_added_monitors!(nodes[1], 1);
815 // AwaitingRemoteRevoke ends here
817 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
818 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
819 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
820 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fee.is_none(), true);
824 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
825 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
826 check_added_monitors!(nodes[0], 1);
827 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
829 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
830 check_added_monitors!(nodes[1], 1);
831 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
833 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
834 check_added_monitors!(nodes[1], 1);
835 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
836 // No commitment_signed so get_event_msg's assert(len == 1) passes
838 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
839 check_added_monitors!(nodes[0], 1);
840 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
842 expect_pending_htlcs_forwardable!(nodes[0]);
844 let events = nodes[0].node.get_and_clear_pending_events();
845 assert_eq!(events.len(), 1);
847 Event::PaymentClaimable { .. } => { },
848 _ => panic!("Unexpected event"),
851 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
853 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
854 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
855 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
856 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
857 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
861 fn test_update_fee() {
862 let chanmon_cfgs = create_chanmon_cfgs(2);
863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
865 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
866 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
867 let channel_id = chan.2;
870 // (1) update_fee/commitment_signed ->
871 // <- (2) revoke_and_ack
872 // .- send (3) commitment_signed
873 // (4) update_fee/commitment_signed ->
874 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
875 // <- (3) commitment_signed delivered
876 // send (6) revoke_and_ack -.
877 // <- (5) deliver revoke_and_ack
878 // (6) deliver revoke_and_ack ->
879 // .- send (7) commitment_signed in response to (4)
880 // <- (7) deliver commitment_signed
883 // Create and deliver (1)...
886 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
887 feerate = *feerate_lock;
888 *feerate_lock = feerate + 20;
890 nodes[0].node.timer_tick_occurred();
891 check_added_monitors!(nodes[0], 1);
893 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
894 assert_eq!(events_0.len(), 1);
895 let (update_msg, commitment_signed) = match events_0[0] {
896 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 } } => {
897 (update_fee.as_ref(), commitment_signed)
899 _ => panic!("Unexpected event"),
901 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
903 // Generate (2) and (3):
904 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
905 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
906 check_added_monitors!(nodes[1], 1);
909 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
910 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
911 check_added_monitors!(nodes[0], 1);
913 // Create and deliver (4)...
915 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
916 *feerate_lock = feerate + 30;
918 nodes[0].node.timer_tick_occurred();
919 check_added_monitors!(nodes[0], 1);
920 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
921 assert_eq!(events_0.len(), 1);
922 let (update_msg, commitment_signed) = match events_0[0] {
923 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 } } => {
924 (update_fee.as_ref(), commitment_signed)
926 _ => panic!("Unexpected event"),
929 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
930 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
931 check_added_monitors!(nodes[1], 1);
933 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
934 // No commitment_signed so get_event_msg's assert(len == 1) passes
936 // Handle (3), creating (6):
937 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
938 check_added_monitors!(nodes[0], 1);
939 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
940 // No commitment_signed so get_event_msg's assert(len == 1) passes
943 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
944 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
945 check_added_monitors!(nodes[0], 1);
947 // Deliver (6), creating (7):
948 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
949 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
950 assert!(commitment_update.update_add_htlcs.is_empty());
951 assert!(commitment_update.update_fulfill_htlcs.is_empty());
952 assert!(commitment_update.update_fail_htlcs.is_empty());
953 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
954 assert!(commitment_update.update_fee.is_none());
955 check_added_monitors!(nodes[1], 1);
958 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
959 check_added_monitors!(nodes[0], 1);
960 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
961 // No commitment_signed so get_event_msg's assert(len == 1) passes
963 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
964 check_added_monitors!(nodes[1], 1);
965 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
967 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
968 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
969 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
970 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
971 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
975 fn fake_network_test() {
976 // Simple test which builds a network of ChannelManagers, connects them to each other, and
977 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
978 let chanmon_cfgs = create_chanmon_cfgs(4);
979 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
980 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
981 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
983 // Create some initial channels
984 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
985 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
986 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
988 // Rebalance the network a bit by relaying one payment through all the channels...
989 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
994 // Send some more payments
995 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
996 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
999 // Test failure packets
1000 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1001 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1003 // Add a new channel that skips 3
1004 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1006 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1007 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1008 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014 // Do some rebalance loop payments, simultaneously
1015 let mut hops = Vec::with_capacity(3);
1016 hops.push(RouteHop {
1017 pubkey: nodes[2].node.get_our_node_id(),
1018 node_features: NodeFeatures::empty(),
1019 short_channel_id: chan_2.0.contents.short_channel_id,
1020 channel_features: ChannelFeatures::empty(),
1022 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1024 hops.push(RouteHop {
1025 pubkey: nodes[3].node.get_our_node_id(),
1026 node_features: NodeFeatures::empty(),
1027 short_channel_id: chan_3.0.contents.short_channel_id,
1028 channel_features: ChannelFeatures::empty(),
1030 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1032 hops.push(RouteHop {
1033 pubkey: nodes[1].node.get_our_node_id(),
1034 node_features: nodes[1].node.node_features(),
1035 short_channel_id: chan_4.0.contents.short_channel_id,
1036 channel_features: nodes[1].node.channel_features(),
1038 cltv_expiry_delta: TEST_FINAL_CLTV,
1040 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;
1041 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;
1042 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;
1044 let mut hops = Vec::with_capacity(3);
1045 hops.push(RouteHop {
1046 pubkey: nodes[3].node.get_our_node_id(),
1047 node_features: NodeFeatures::empty(),
1048 short_channel_id: chan_4.0.contents.short_channel_id,
1049 channel_features: ChannelFeatures::empty(),
1051 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1053 hops.push(RouteHop {
1054 pubkey: nodes[2].node.get_our_node_id(),
1055 node_features: NodeFeatures::empty(),
1056 short_channel_id: chan_3.0.contents.short_channel_id,
1057 channel_features: ChannelFeatures::empty(),
1059 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1061 hops.push(RouteHop {
1062 pubkey: nodes[1].node.get_our_node_id(),
1063 node_features: nodes[1].node.node_features(),
1064 short_channel_id: chan_2.0.contents.short_channel_id,
1065 channel_features: nodes[1].node.channel_features(),
1067 cltv_expiry_delta: TEST_FINAL_CLTV,
1069 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;
1070 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;
1071 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;
1073 // Claim the rebalances...
1074 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1075 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1077 // Close down the channels...
1078 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1079 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1080 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1081 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1082 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1083 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1084 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1085 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1086 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1087 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1088 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1089 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1093 fn holding_cell_htlc_counting() {
1094 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1095 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1096 // commitment dance rounds.
1097 let chanmon_cfgs = create_chanmon_cfgs(3);
1098 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1099 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1100 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1101 create_announced_chan_between_nodes(&nodes, 0, 1);
1102 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1104 let mut payments = Vec::new();
1105 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1106 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1107 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1108 payments.push((payment_preimage, payment_hash));
1110 check_added_monitors!(nodes[1], 1);
1112 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1113 assert_eq!(events.len(), 1);
1114 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1115 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1117 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1118 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1120 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1122 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 },
1123 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1124 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1125 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1128 // This should also be true if we try to forward a payment.
1129 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1131 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1132 check_added_monitors!(nodes[0], 1);
1135 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1136 assert_eq!(events.len(), 1);
1137 let payment_event = SendEvent::from_event(events.pop().unwrap());
1138 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1140 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1141 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1142 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1143 // fails), the second will process the resulting failure and fail the HTLC backward.
1144 expect_pending_htlcs_forwardable!(nodes[1]);
1145 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 }]);
1146 check_added_monitors!(nodes[1], 1);
1148 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1149 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1150 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1152 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1154 // Now forward all the pending HTLCs and claim them back
1155 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1156 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1157 check_added_monitors!(nodes[2], 1);
1159 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1160 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1161 check_added_monitors!(nodes[1], 1);
1162 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1164 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1165 check_added_monitors!(nodes[1], 1);
1166 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1168 for ref update in as_updates.update_add_htlcs.iter() {
1169 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1171 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1172 check_added_monitors!(nodes[2], 1);
1173 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1174 check_added_monitors!(nodes[2], 1);
1175 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1177 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1178 check_added_monitors!(nodes[1], 1);
1179 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1180 check_added_monitors!(nodes[1], 1);
1181 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1183 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1184 check_added_monitors!(nodes[2], 1);
1186 expect_pending_htlcs_forwardable!(nodes[2]);
1188 let events = nodes[2].node.get_and_clear_pending_events();
1189 assert_eq!(events.len(), payments.len());
1190 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1192 &Event::PaymentClaimable { ref payment_hash, .. } => {
1193 assert_eq!(*payment_hash, *hash);
1195 _ => panic!("Unexpected event"),
1199 for (preimage, _) in payments.drain(..) {
1200 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1203 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1207 fn duplicate_htlc_test() {
1208 // Test that we accept duplicate payment_hash HTLCs across the network and that
1209 // claiming/failing them are all separate and don't affect each other
1210 let chanmon_cfgs = create_chanmon_cfgs(6);
1211 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1212 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1213 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1215 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1216 create_announced_chan_between_nodes(&nodes, 0, 3);
1217 create_announced_chan_between_nodes(&nodes, 1, 3);
1218 create_announced_chan_between_nodes(&nodes, 2, 3);
1219 create_announced_chan_between_nodes(&nodes, 3, 4);
1220 create_announced_chan_between_nodes(&nodes, 3, 5);
1222 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1224 *nodes[0].network_payment_count.borrow_mut() -= 1;
1225 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1227 *nodes[0].network_payment_count.borrow_mut() -= 1;
1228 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1230 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1231 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1232 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1236 fn test_duplicate_htlc_different_direction_onchain() {
1237 // Test that ChannelMonitor doesn't generate 2 preimage txn
1238 // when we have 2 HTLCs with same preimage that go across a node
1239 // in opposite directions, even with the same payment secret.
1240 let chanmon_cfgs = create_chanmon_cfgs(2);
1241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1243 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1245 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1248 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1250 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1252 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1253 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1254 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1256 // Provide preimage to node 0 by claiming payment
1257 nodes[0].node.claim_funds(payment_preimage);
1258 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1259 check_added_monitors!(nodes[0], 1);
1261 // Broadcast node 1 commitment txn
1262 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1264 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1265 let mut has_both_htlcs = 0; // check htlcs match ones committed
1266 for outp in remote_txn[0].output.iter() {
1267 if outp.value == 800_000 / 1000 {
1268 has_both_htlcs += 1;
1269 } else if outp.value == 900_000 / 1000 {
1270 has_both_htlcs += 1;
1273 assert_eq!(has_both_htlcs, 2);
1275 mine_transaction(&nodes[0], &remote_txn[0]);
1276 check_added_monitors!(nodes[0], 1);
1277 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1278 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1280 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1281 assert_eq!(claim_txn.len(), 3);
1283 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1284 check_spends!(claim_txn[1], remote_txn[0]);
1285 check_spends!(claim_txn[2], remote_txn[0]);
1286 let preimage_tx = &claim_txn[0];
1287 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1288 (&claim_txn[1], &claim_txn[2])
1290 (&claim_txn[2], &claim_txn[1])
1293 assert_eq!(preimage_tx.input.len(), 1);
1294 assert_eq!(preimage_bump_tx.input.len(), 1);
1296 assert_eq!(preimage_tx.input.len(), 1);
1297 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1298 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1300 assert_eq!(timeout_tx.input.len(), 1);
1301 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1302 check_spends!(timeout_tx, remote_txn[0]);
1303 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1305 let events = nodes[0].node.get_and_clear_pending_msg_events();
1306 assert_eq!(events.len(), 3);
1309 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1310 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1311 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1312 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1314 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, .. } } => {
1315 assert!(update_add_htlcs.is_empty());
1316 assert!(update_fail_htlcs.is_empty());
1317 assert_eq!(update_fulfill_htlcs.len(), 1);
1318 assert!(update_fail_malformed_htlcs.is_empty());
1319 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1321 _ => panic!("Unexpected event"),
1327 fn test_basic_channel_reserve() {
1328 let chanmon_cfgs = create_chanmon_cfgs(2);
1329 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1330 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1331 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1332 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1334 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1335 let channel_reserve = chan_stat.channel_reserve_msat;
1337 // The 2* and +1 are for the fee spike reserve.
1338 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));
1339 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1340 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1341 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1343 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1345 &APIError::ChannelUnavailable{ref err} =>
1346 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1347 _ => panic!("Unexpected error variant"),
1350 _ => panic!("Unexpected error variant"),
1352 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1353 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1355 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1359 fn test_fee_spike_violation_fails_htlc() {
1360 let chanmon_cfgs = create_chanmon_cfgs(2);
1361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1366 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1367 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1368 let secp_ctx = Secp256k1::new();
1369 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1371 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1373 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1374 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1375 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1376 let msg = msgs::UpdateAddHTLC {
1379 amount_msat: htlc_msat,
1380 payment_hash: payment_hash,
1381 cltv_expiry: htlc_cltv,
1382 onion_routing_packet: onion_packet,
1385 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1387 // Now manually create the commitment_signed message corresponding to the update_add
1388 // nodes[0] just sent. In the code for construction of this message, "local" refers
1389 // to the sender of the message, and "remote" refers to the receiver.
1391 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1393 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1395 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1396 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1397 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1398 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1399 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1400 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1401 let chan_signer = local_chan.get_signer();
1402 // Make the signer believe we validated another commitment, so we can release the secret
1403 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1405 let pubkeys = chan_signer.pubkeys();
1406 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1407 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1408 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1409 chan_signer.pubkeys().funding_pubkey)
1411 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1412 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1413 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1414 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1415 let chan_signer = remote_chan.get_signer();
1416 let pubkeys = chan_signer.pubkeys();
1417 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1418 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1419 chan_signer.pubkeys().funding_pubkey)
1422 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1423 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1424 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1426 // Build the remote commitment transaction so we can sign it, and then later use the
1427 // signature for the commitment_signed message.
1428 let local_chan_balance = 1313;
1430 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1432 amount_msat: 3460001,
1433 cltv_expiry: htlc_cltv,
1435 transaction_output_index: Some(1),
1438 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1441 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1442 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1443 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1444 let local_chan_signer = local_chan.get_signer();
1445 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1449 local_chan.opt_anchors(), local_funding, remote_funding,
1450 commit_tx_keys.clone(),
1452 &mut vec![(accepted_htlc_info, ())],
1453 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1455 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1458 let commit_signed_msg = msgs::CommitmentSigned {
1461 htlc_signatures: res.1
1464 // Send the commitment_signed message to the nodes[1].
1465 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1466 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1468 // Send the RAA to nodes[1].
1469 let raa_msg = msgs::RevokeAndACK {
1471 per_commitment_secret: local_secret,
1472 next_per_commitment_point: next_local_point
1474 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1476 let events = nodes[1].node.get_and_clear_pending_msg_events();
1477 assert_eq!(events.len(), 1);
1478 // Make sure the HTLC failed in the way we expect.
1480 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1481 assert_eq!(update_fail_htlcs.len(), 1);
1482 update_fail_htlcs[0].clone()
1484 _ => panic!("Unexpected event"),
1486 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1487 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1489 check_added_monitors!(nodes[1], 2);
1493 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1494 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1495 // Set the fee rate for the channel very high, to the point where the fundee
1496 // sending any above-dust amount would result in a channel reserve violation.
1497 // In this test we check that we would be prevented from sending an HTLC in
1499 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1502 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1503 let default_config = UserConfig::default();
1504 let opt_anchors = false;
1506 let mut push_amt = 100_000_000;
1507 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1509 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1511 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1513 // Sending exactly enough to hit the reserve amount should be accepted
1514 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1515 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1518 // However one more HTLC should be significantly over the reserve amount and fail.
1519 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1520 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 },
1521 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1522 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1523 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);
1527 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1528 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1529 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1532 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1533 let default_config = UserConfig::default();
1534 let opt_anchors = false;
1536 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1537 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1538 // transaction fee with 0 HTLCs (183 sats)).
1539 let mut push_amt = 100_000_000;
1540 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1541 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1542 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1544 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1545 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1546 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1549 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1550 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1551 let secp_ctx = Secp256k1::new();
1552 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1553 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1554 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1555 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1556 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1557 let msg = msgs::UpdateAddHTLC {
1559 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1560 amount_msat: htlc_msat,
1561 payment_hash: payment_hash,
1562 cltv_expiry: htlc_cltv,
1563 onion_routing_packet: onion_packet,
1566 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1567 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1568 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);
1569 assert_eq!(nodes[0].node.list_channels().len(), 0);
1570 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1571 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1572 check_added_monitors!(nodes[0], 1);
1573 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() });
1577 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1578 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1579 // calculating our commitment transaction fee (this was previously broken).
1580 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1581 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1585 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1586 let default_config = UserConfig::default();
1587 let opt_anchors = false;
1589 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1590 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1591 // transaction fee with 0 HTLCs (183 sats)).
1592 let mut push_amt = 100_000_000;
1593 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1594 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1595 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1597 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1598 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1599 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1600 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1601 // commitment transaction fee.
1602 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1604 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1605 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1606 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1609 // One more than the dust amt should fail, however.
1610 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1611 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 },
1612 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1616 fn test_chan_init_feerate_unaffordability() {
1617 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1618 // channel reserve and feerate requirements.
1619 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1620 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1624 let default_config = UserConfig::default();
1625 let opt_anchors = false;
1627 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1629 let mut push_amt = 100_000_000;
1630 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1631 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1632 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1634 // During open, we don't have a "counterparty channel reserve" to check against, so that
1635 // requirement only comes into play on the open_channel handling side.
1636 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1637 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1638 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1639 open_channel_msg.push_msat += 1;
1640 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1642 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1643 assert_eq!(msg_events.len(), 1);
1644 match msg_events[0] {
1645 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1646 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1648 _ => panic!("Unexpected event"),
1653 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1654 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1655 // calculating our counterparty's commitment transaction fee (this was previously broken).
1656 let chanmon_cfgs = create_chanmon_cfgs(2);
1657 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1658 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1659 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1660 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1662 let payment_amt = 46000; // Dust amount
1663 // In the previous code, these first four payments would succeed.
1664 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1665 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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);
1674 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1677 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1678 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1679 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1684 let chanmon_cfgs = create_chanmon_cfgs(3);
1685 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1686 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1687 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1688 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1689 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1692 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1693 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1694 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1695 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1697 // Add a 2* and +1 for the fee spike reserve.
1698 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1699 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;
1700 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1702 // Add a pending HTLC.
1703 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1704 let payment_event_1 = {
1705 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1706 check_added_monitors!(nodes[0], 1);
1708 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1709 assert_eq!(events.len(), 1);
1710 SendEvent::from_event(events.remove(0))
1712 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1714 // Attempt to trigger a channel reserve violation --> payment failure.
1715 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1716 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;
1717 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1718 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1720 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1721 let secp_ctx = Secp256k1::new();
1722 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1723 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1724 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1725 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1726 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1727 let msg = msgs::UpdateAddHTLC {
1730 amount_msat: htlc_msat + 1,
1731 payment_hash: our_payment_hash_1,
1732 cltv_expiry: htlc_cltv,
1733 onion_routing_packet: onion_packet,
1736 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1737 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1738 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1739 assert_eq!(nodes[1].node.list_channels().len(), 1);
1740 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1741 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1742 check_added_monitors!(nodes[1], 1);
1743 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1747 fn test_inbound_outbound_capacity_is_not_zero() {
1748 let chanmon_cfgs = create_chanmon_cfgs(2);
1749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1751 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1752 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1753 let channels0 = node_chanmgrs[0].list_channels();
1754 let channels1 = node_chanmgrs[1].list_channels();
1755 let default_config = UserConfig::default();
1756 assert_eq!(channels0.len(), 1);
1757 assert_eq!(channels1.len(), 1);
1759 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1760 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1761 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1763 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1764 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1767 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1768 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1772 fn test_channel_reserve_holding_cell_htlcs() {
1773 let chanmon_cfgs = create_chanmon_cfgs(3);
1774 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1775 // When this test was written, the default base fee floated based on the HTLC count.
1776 // It is now fixed, so we simply set the fee to the expected value here.
1777 let mut config = test_default_channel_config();
1778 config.channel_config.forwarding_fee_base_msat = 239;
1779 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1780 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1781 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1782 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1784 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1785 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1787 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1788 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1790 macro_rules! expect_forward {
1792 let mut events = $node.node.get_and_clear_pending_msg_events();
1793 assert_eq!(events.len(), 1);
1794 check_added_monitors!($node, 1);
1795 let payment_event = SendEvent::from_event(events.remove(0));
1800 let feemsat = 239; // set above
1801 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1802 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1803 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1805 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1807 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1809 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1810 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1811 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);
1812 route.paths[0].last_mut().unwrap().fee_msat += 1;
1813 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1815 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 },
1816 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)));
1817 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1818 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);
1821 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1822 // nodes[0]'s wealth
1824 let amt_msat = recv_value_0 + total_fee_msat;
1825 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1826 // Also, ensure that each payment has enough to be over the dust limit to
1827 // ensure it'll be included in each commit tx fee calculation.
1828 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1829 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1830 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1834 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1835 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1836 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1837 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1838 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1840 let (stat01_, stat11_, stat12_, stat22_) = (
1841 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1842 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1843 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1844 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1847 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1848 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1849 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1850 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1851 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1854 // adding pending output.
1855 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1856 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1857 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1858 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1859 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1860 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1861 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1862 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1863 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1865 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1866 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1867 let amt_msat_1 = recv_value_1 + total_fee_msat;
1869 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);
1870 let payment_event_1 = {
1871 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1872 check_added_monitors!(nodes[0], 1);
1874 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1875 assert_eq!(events.len(), 1);
1876 SendEvent::from_event(events.remove(0))
1878 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1880 // channel reserve test with htlc pending output > 0
1881 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1883 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1884 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 },
1885 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1889 // split the rest to test holding cell
1890 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1891 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1892 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1893 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1895 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1896 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);
1899 // now see if they go through on both sides
1900 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);
1901 // but this will stuck in the holding cell
1902 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1903 check_added_monitors!(nodes[0], 0);
1904 let events = nodes[0].node.get_and_clear_pending_events();
1905 assert_eq!(events.len(), 0);
1907 // test with outbound holding cell amount > 0
1909 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1910 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 },
1911 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1912 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1913 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1916 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);
1917 // this will also stuck in the holding cell
1918 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1919 check_added_monitors!(nodes[0], 0);
1920 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1921 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1923 // flush the pending htlc
1924 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1925 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1926 check_added_monitors!(nodes[1], 1);
1928 // the pending htlc should be promoted to committed
1929 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1930 check_added_monitors!(nodes[0], 1);
1931 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1933 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1934 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1935 // No commitment_signed so get_event_msg's assert(len == 1) passes
1936 check_added_monitors!(nodes[0], 1);
1938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1939 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1940 check_added_monitors!(nodes[1], 1);
1942 expect_pending_htlcs_forwardable!(nodes[1]);
1944 let ref payment_event_11 = expect_forward!(nodes[1]);
1945 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1946 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1948 expect_pending_htlcs_forwardable!(nodes[2]);
1949 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1951 // flush the htlcs in the holding cell
1952 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1954 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1955 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1956 expect_pending_htlcs_forwardable!(nodes[1]);
1958 let ref payment_event_3 = expect_forward!(nodes[1]);
1959 assert_eq!(payment_event_3.msgs.len(), 2);
1960 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1961 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1963 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1964 expect_pending_htlcs_forwardable!(nodes[2]);
1966 let events = nodes[2].node.get_and_clear_pending_events();
1967 assert_eq!(events.len(), 2);
1969 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1970 assert_eq!(our_payment_hash_21, *payment_hash);
1971 assert_eq!(recv_value_21, amount_msat);
1972 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1973 assert_eq!(via_channel_id, Some(chan_2.2));
1975 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1976 assert!(payment_preimage.is_none());
1977 assert_eq!(our_payment_secret_21, *payment_secret);
1979 _ => panic!("expected PaymentPurpose::InvoicePayment")
1982 _ => panic!("Unexpected event"),
1985 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1986 assert_eq!(our_payment_hash_22, *payment_hash);
1987 assert_eq!(recv_value_22, amount_msat);
1988 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1989 assert_eq!(via_channel_id, Some(chan_2.2));
1991 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1992 assert!(payment_preimage.is_none());
1993 assert_eq!(our_payment_secret_22, *payment_secret);
1995 _ => panic!("expected PaymentPurpose::InvoicePayment")
1998 _ => panic!("Unexpected event"),
2001 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2002 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2003 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2005 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2006 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2007 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2009 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2010 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);
2011 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2012 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2013 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2015 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2016 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2020 fn channel_reserve_in_flight_removes() {
2021 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2022 // can send to its counterparty, but due to update ordering, the other side may not yet have
2023 // considered those HTLCs fully removed.
2024 // This tests that we don't count HTLCs which will not be included in the next remote
2025 // commitment transaction towards the reserve value (as it implies no commitment transaction
2026 // will be generated which violates the remote reserve value).
2027 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2029 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2030 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2031 // you only consider the value of the first HTLC, it may not),
2032 // * start routing a third HTLC from A to B,
2033 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2034 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2035 // * deliver the first fulfill from B
2036 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2038 // * deliver A's response CS and RAA.
2039 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2040 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2041 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2042 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2043 let chanmon_cfgs = create_chanmon_cfgs(2);
2044 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2045 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2046 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2047 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2049 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2050 // Route the first two HTLCs.
2051 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2052 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2053 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2055 // Start routing the third HTLC (this is just used to get everyone in the right state).
2056 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2058 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2059 check_added_monitors!(nodes[0], 1);
2060 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2061 assert_eq!(events.len(), 1);
2062 SendEvent::from_event(events.remove(0))
2065 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2066 // initial fulfill/CS.
2067 nodes[1].node.claim_funds(payment_preimage_1);
2068 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2069 check_added_monitors!(nodes[1], 1);
2070 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2072 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2073 // remove the second HTLC when we send the HTLC back from B to A.
2074 nodes[1].node.claim_funds(payment_preimage_2);
2075 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2076 check_added_monitors!(nodes[1], 1);
2077 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2079 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2080 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2081 check_added_monitors!(nodes[0], 1);
2082 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2083 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2086 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2087 check_added_monitors!(nodes[1], 1);
2088 // B is already AwaitingRAA, so cant generate a CS here
2089 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2091 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2092 check_added_monitors!(nodes[1], 1);
2093 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2095 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2096 check_added_monitors!(nodes[0], 1);
2097 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2099 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2100 check_added_monitors!(nodes[1], 1);
2101 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2103 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2104 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2105 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2106 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2107 // on-chain as necessary).
2108 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2109 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2110 check_added_monitors!(nodes[0], 1);
2111 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2112 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2114 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2115 check_added_monitors!(nodes[1], 1);
2116 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2118 expect_pending_htlcs_forwardable!(nodes[1]);
2119 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2121 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2122 // resolve the second HTLC from A's point of view.
2123 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2124 check_added_monitors!(nodes[0], 1);
2125 expect_payment_path_successful!(nodes[0]);
2126 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2128 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2129 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2130 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2132 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2133 check_added_monitors!(nodes[1], 1);
2134 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2135 assert_eq!(events.len(), 1);
2136 SendEvent::from_event(events.remove(0))
2139 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2140 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2141 check_added_monitors!(nodes[0], 1);
2142 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2144 // Now just resolve all the outstanding messages/HTLCs for completeness...
2146 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2147 check_added_monitors!(nodes[1], 1);
2148 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2150 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2151 check_added_monitors!(nodes[1], 1);
2153 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2154 check_added_monitors!(nodes[0], 1);
2155 expect_payment_path_successful!(nodes[0]);
2156 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2158 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2159 check_added_monitors!(nodes[1], 1);
2160 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2162 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163 check_added_monitors!(nodes[0], 1);
2165 expect_pending_htlcs_forwardable!(nodes[0]);
2166 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2168 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2169 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2173 fn channel_monitor_network_test() {
2174 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2175 // tests that ChannelMonitor is able to recover from various states.
2176 let chanmon_cfgs = create_chanmon_cfgs(5);
2177 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2178 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2179 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2181 // Create some initial channels
2182 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2183 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2184 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2185 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2187 // Make sure all nodes are at the same starting height
2188 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2189 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2190 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2191 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2192 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2194 // Rebalance the network a bit by relaying one payment through all the channels...
2195 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2196 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2197 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2198 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2200 // Simple case with no pending HTLCs:
2201 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2202 check_added_monitors!(nodes[1], 1);
2203 check_closed_broadcast!(nodes[1], true);
2205 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2206 assert_eq!(node_txn.len(), 1);
2207 mine_transaction(&nodes[0], &node_txn[0]);
2208 check_added_monitors!(nodes[0], 1);
2209 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2211 check_closed_broadcast!(nodes[0], true);
2212 assert_eq!(nodes[0].node.list_channels().len(), 0);
2213 assert_eq!(nodes[1].node.list_channels().len(), 1);
2214 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2215 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2217 // One pending HTLC is discarded by the force-close:
2218 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2220 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2221 // broadcasted until we reach the timelock time).
2222 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2223 check_closed_broadcast!(nodes[1], true);
2224 check_added_monitors!(nodes[1], 1);
2226 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2227 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2228 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2229 mine_transaction(&nodes[2], &node_txn[0]);
2230 check_added_monitors!(nodes[2], 1);
2231 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2233 check_closed_broadcast!(nodes[2], true);
2234 assert_eq!(nodes[1].node.list_channels().len(), 0);
2235 assert_eq!(nodes[2].node.list_channels().len(), 1);
2236 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2237 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2239 macro_rules! claim_funds {
2240 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2242 $node.node.claim_funds($preimage);
2243 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2244 check_added_monitors!($node, 1);
2246 let events = $node.node.get_and_clear_pending_msg_events();
2247 assert_eq!(events.len(), 1);
2249 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2250 assert!(update_add_htlcs.is_empty());
2251 assert!(update_fail_htlcs.is_empty());
2252 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2254 _ => panic!("Unexpected event"),
2260 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2261 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2262 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2263 check_added_monitors!(nodes[2], 1);
2264 check_closed_broadcast!(nodes[2], true);
2265 let node2_commitment_txid;
2267 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2268 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2269 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2270 node2_commitment_txid = node_txn[0].txid();
2272 // Claim the payment on nodes[3], giving it knowledge of the preimage
2273 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2274 mine_transaction(&nodes[3], &node_txn[0]);
2275 check_added_monitors!(nodes[3], 1);
2276 check_preimage_claim(&nodes[3], &node_txn);
2278 check_closed_broadcast!(nodes[3], true);
2279 assert_eq!(nodes[2].node.list_channels().len(), 0);
2280 assert_eq!(nodes[3].node.list_channels().len(), 1);
2281 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2282 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2284 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2285 // confusing us in the following tests.
2286 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2288 // One pending HTLC to time out:
2289 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2290 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2293 let (close_chan_update_1, close_chan_update_2) = {
2294 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2295 let events = nodes[3].node.get_and_clear_pending_msg_events();
2296 assert_eq!(events.len(), 2);
2297 let close_chan_update_1 = match events[0] {
2298 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2301 _ => panic!("Unexpected event"),
2304 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2305 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2307 _ => panic!("Unexpected event"),
2309 check_added_monitors!(nodes[3], 1);
2311 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2313 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2314 node_txn.retain(|tx| {
2315 if tx.input[0].previous_output.txid == node2_commitment_txid {
2321 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2323 // Claim the payment on nodes[4], giving it knowledge of the preimage
2324 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2326 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2327 let events = nodes[4].node.get_and_clear_pending_msg_events();
2328 assert_eq!(events.len(), 2);
2329 let close_chan_update_2 = match events[0] {
2330 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2333 _ => panic!("Unexpected event"),
2336 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2337 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2339 _ => panic!("Unexpected event"),
2341 check_added_monitors!(nodes[4], 1);
2342 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2344 mine_transaction(&nodes[4], &node_txn[0]);
2345 check_preimage_claim(&nodes[4], &node_txn);
2346 (close_chan_update_1, close_chan_update_2)
2348 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2349 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2350 assert_eq!(nodes[3].node.list_channels().len(), 0);
2351 assert_eq!(nodes[4].node.list_channels().len(), 0);
2353 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2354 ChannelMonitorUpdateStatus::Completed);
2355 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2356 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2360 fn test_justice_tx() {
2361 // Test justice txn built on revoked HTLC-Success tx, against both sides
2362 let mut alice_config = UserConfig::default();
2363 alice_config.channel_handshake_config.announced_channel = true;
2364 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2365 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2366 let mut bob_config = UserConfig::default();
2367 bob_config.channel_handshake_config.announced_channel = true;
2368 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2369 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2370 let user_cfgs = [Some(alice_config), Some(bob_config)];
2371 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2372 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2373 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2376 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2377 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2378 // Create some new channels:
2379 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2381 // A pending HTLC which will be revoked:
2382 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2383 // Get the will-be-revoked local txn from nodes[0]
2384 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2385 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2386 assert_eq!(revoked_local_txn[0].input.len(), 1);
2387 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2388 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2389 assert_eq!(revoked_local_txn[1].input.len(), 1);
2390 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2391 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2392 // Revoke the old state
2393 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2396 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2398 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2399 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2400 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2402 check_spends!(node_txn[0], revoked_local_txn[0]);
2403 node_txn.swap_remove(0);
2405 check_added_monitors!(nodes[1], 1);
2406 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2407 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2409 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2410 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2411 // Verify broadcast of revoked HTLC-timeout
2412 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2413 check_added_monitors!(nodes[0], 1);
2414 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2415 // Broadcast revoked HTLC-timeout on node 1
2416 mine_transaction(&nodes[1], &node_txn[1]);
2417 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2419 get_announce_close_broadcast_events(&nodes, 0, 1);
2421 assert_eq!(nodes[0].node.list_channels().len(), 0);
2422 assert_eq!(nodes[1].node.list_channels().len(), 0);
2424 // We test justice_tx build by A on B's revoked HTLC-Success tx
2425 // Create some new channels:
2426 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2428 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2432 // A pending HTLC which will be revoked:
2433 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2434 // Get the will-be-revoked local txn from B
2435 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2436 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2437 assert_eq!(revoked_local_txn[0].input.len(), 1);
2438 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2439 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2440 // Revoke the old state
2441 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2443 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2445 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2446 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2447 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2449 check_spends!(node_txn[0], revoked_local_txn[0]);
2450 node_txn.swap_remove(0);
2452 check_added_monitors!(nodes[0], 1);
2453 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2455 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2456 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2457 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2458 check_added_monitors!(nodes[1], 1);
2459 mine_transaction(&nodes[0], &node_txn[1]);
2460 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2461 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2463 get_announce_close_broadcast_events(&nodes, 0, 1);
2464 assert_eq!(nodes[0].node.list_channels().len(), 0);
2465 assert_eq!(nodes[1].node.list_channels().len(), 0);
2469 fn revoked_output_claim() {
2470 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2471 // transaction is broadcast by its counterparty
2472 let chanmon_cfgs = create_chanmon_cfgs(2);
2473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2475 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2476 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2477 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2478 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2479 assert_eq!(revoked_local_txn.len(), 1);
2480 // Only output is the full channel value back to nodes[0]:
2481 assert_eq!(revoked_local_txn[0].output.len(), 1);
2482 // Send a payment through, updating everyone's latest commitment txn
2483 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2485 // Inform nodes[1] that nodes[0] broadcast a stale tx
2486 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2487 check_added_monitors!(nodes[1], 1);
2488 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2489 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2490 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2492 check_spends!(node_txn[0], revoked_local_txn[0]);
2494 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2495 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2496 get_announce_close_broadcast_events(&nodes, 0, 1);
2497 check_added_monitors!(nodes[0], 1);
2498 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2502 fn claim_htlc_outputs_shared_tx() {
2503 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2504 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2505 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2510 // Create some new channel:
2511 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2513 // Rebalance the network to generate htlc in the two directions
2514 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2515 // 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
2516 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2517 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2519 // Get the will-be-revoked local txn from node[0]
2520 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2521 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2522 assert_eq!(revoked_local_txn[0].input.len(), 1);
2523 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2524 assert_eq!(revoked_local_txn[1].input.len(), 1);
2525 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2526 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2527 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2529 //Revoke the old state
2530 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2533 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2534 check_added_monitors!(nodes[0], 1);
2535 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2536 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2537 check_added_monitors!(nodes[1], 1);
2538 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2539 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2540 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2542 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2543 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2545 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2546 check_spends!(node_txn[0], revoked_local_txn[0]);
2548 let mut witness_lens = BTreeSet::new();
2549 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2550 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2551 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2552 assert_eq!(witness_lens.len(), 3);
2553 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2554 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2555 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2557 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2558 // ANTI_REORG_DELAY confirmations.
2559 mine_transaction(&nodes[1], &node_txn[0]);
2560 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2561 expect_payment_failed!(nodes[1], payment_hash_2, false);
2563 get_announce_close_broadcast_events(&nodes, 0, 1);
2564 assert_eq!(nodes[0].node.list_channels().len(), 0);
2565 assert_eq!(nodes[1].node.list_channels().len(), 0);
2569 fn claim_htlc_outputs_single_tx() {
2570 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2571 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2572 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2575 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2577 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2579 // Rebalance the network to generate htlc in the two directions
2580 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2581 // 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
2582 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2583 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2584 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2586 // Get the will-be-revoked local txn from node[0]
2587 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2589 //Revoke the old state
2590 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2593 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2594 check_added_monitors!(nodes[0], 1);
2595 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2596 check_added_monitors!(nodes[1], 1);
2597 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2598 let mut events = nodes[0].node.get_and_clear_pending_events();
2599 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2600 match events.last().unwrap() {
2601 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2602 _ => panic!("Unexpected event"),
2605 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2606 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2608 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2609 assert_eq!(node_txn.len(), 7);
2611 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2612 assert_eq!(node_txn[0].input.len(), 1);
2613 check_spends!(node_txn[0], chan_1.3);
2614 assert_eq!(node_txn[1].input.len(), 1);
2615 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2616 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2617 check_spends!(node_txn[1], node_txn[0]);
2619 // Justice transactions are indices 2-3-4
2620 assert_eq!(node_txn[2].input.len(), 1);
2621 assert_eq!(node_txn[3].input.len(), 1);
2622 assert_eq!(node_txn[4].input.len(), 1);
2624 check_spends!(node_txn[2], revoked_local_txn[0]);
2625 check_spends!(node_txn[3], revoked_local_txn[0]);
2626 check_spends!(node_txn[4], revoked_local_txn[0]);
2628 let mut witness_lens = BTreeSet::new();
2629 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2630 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2631 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2632 assert_eq!(witness_lens.len(), 3);
2633 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2634 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2635 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2637 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2638 // ANTI_REORG_DELAY confirmations.
2639 mine_transaction(&nodes[1], &node_txn[2]);
2640 mine_transaction(&nodes[1], &node_txn[3]);
2641 mine_transaction(&nodes[1], &node_txn[4]);
2642 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2643 expect_payment_failed!(nodes[1], payment_hash_2, false);
2645 get_announce_close_broadcast_events(&nodes, 0, 1);
2646 assert_eq!(nodes[0].node.list_channels().len(), 0);
2647 assert_eq!(nodes[1].node.list_channels().len(), 0);
2651 fn test_htlc_on_chain_success() {
2652 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2653 // the preimage backward accordingly. So here we test that ChannelManager is
2654 // broadcasting the right event to other nodes in payment path.
2655 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2656 // A --------------------> B ----------------------> C (preimage)
2657 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2658 // commitment transaction was broadcast.
2659 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2661 // B should be able to claim via preimage if A then broadcasts its local tx.
2662 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2663 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2664 // PaymentSent event).
2666 let chanmon_cfgs = create_chanmon_cfgs(3);
2667 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2668 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2669 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2671 // Create some initial channels
2672 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2673 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2675 // Ensure all nodes are at the same height
2676 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2677 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2678 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2679 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2681 // Rebalance the network a bit by relaying one payment through all the channels...
2682 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2683 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2685 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2686 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2688 // Broadcast legit commitment tx from C on B's chain
2689 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2690 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2691 assert_eq!(commitment_tx.len(), 1);
2692 check_spends!(commitment_tx[0], chan_2.3);
2693 nodes[2].node.claim_funds(our_payment_preimage);
2694 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2695 nodes[2].node.claim_funds(our_payment_preimage_2);
2696 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2697 check_added_monitors!(nodes[2], 2);
2698 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2699 assert!(updates.update_add_htlcs.is_empty());
2700 assert!(updates.update_fail_htlcs.is_empty());
2701 assert!(updates.update_fail_malformed_htlcs.is_empty());
2702 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2704 mine_transaction(&nodes[2], &commitment_tx[0]);
2705 check_closed_broadcast!(nodes[2], true);
2706 check_added_monitors!(nodes[2], 1);
2707 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2708 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2709 assert_eq!(node_txn.len(), 2);
2710 check_spends!(node_txn[0], commitment_tx[0]);
2711 check_spends!(node_txn[1], commitment_tx[0]);
2712 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2713 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2714 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2715 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2716 assert_eq!(node_txn[0].lock_time.0, 0);
2717 assert_eq!(node_txn[1].lock_time.0, 0);
2719 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2720 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2721 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2722 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2724 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2725 assert_eq!(added_monitors.len(), 1);
2726 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2727 added_monitors.clear();
2729 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2730 assert_eq!(forwarded_events.len(), 3);
2731 match forwarded_events[0] {
2732 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2733 _ => panic!("Unexpected event"),
2735 let chan_id = Some(chan_1.2);
2736 match forwarded_events[1] {
2737 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2738 assert_eq!(fee_earned_msat, Some(1000));
2739 assert_eq!(prev_channel_id, chan_id);
2740 assert_eq!(claim_from_onchain_tx, true);
2741 assert_eq!(next_channel_id, Some(chan_2.2));
2742 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2746 match forwarded_events[2] {
2747 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2748 assert_eq!(fee_earned_msat, Some(1000));
2749 assert_eq!(prev_channel_id, chan_id);
2750 assert_eq!(claim_from_onchain_tx, true);
2751 assert_eq!(next_channel_id, Some(chan_2.2));
2752 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2756 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2758 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2759 assert_eq!(added_monitors.len(), 2);
2760 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2761 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2762 added_monitors.clear();
2764 assert_eq!(events.len(), 3);
2766 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2767 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2769 match nodes_2_event {
2770 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2771 _ => panic!("Unexpected event"),
2774 match nodes_0_event {
2775 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, .. } } => {
2776 assert!(update_add_htlcs.is_empty());
2777 assert!(update_fail_htlcs.is_empty());
2778 assert_eq!(update_fulfill_htlcs.len(), 1);
2779 assert!(update_fail_malformed_htlcs.is_empty());
2780 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2782 _ => panic!("Unexpected event"),
2785 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2787 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2788 _ => panic!("Unexpected event"),
2791 macro_rules! check_tx_local_broadcast {
2792 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2793 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2794 assert_eq!(node_txn.len(), 2);
2795 // Node[1]: 2 * HTLC-timeout tx
2796 // Node[0]: 2 * HTLC-timeout tx
2797 check_spends!(node_txn[0], $commitment_tx);
2798 check_spends!(node_txn[1], $commitment_tx);
2799 assert_ne!(node_txn[0].lock_time.0, 0);
2800 assert_ne!(node_txn[1].lock_time.0, 0);
2802 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2803 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2804 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2805 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2807 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2808 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2809 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2810 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2815 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2816 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2818 // Broadcast legit commitment tx from A on B's chain
2819 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2820 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2821 check_spends!(node_a_commitment_tx[0], chan_1.3);
2822 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2823 check_closed_broadcast!(nodes[1], true);
2824 check_added_monitors!(nodes[1], 1);
2825 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2826 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2827 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2828 let commitment_spend =
2829 if node_txn.len() == 1 {
2832 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2833 // FullBlockViaListen
2834 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2835 check_spends!(node_txn[1], commitment_tx[0]);
2836 check_spends!(node_txn[2], commitment_tx[0]);
2837 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2840 check_spends!(node_txn[0], commitment_tx[0]);
2841 check_spends!(node_txn[1], commitment_tx[0]);
2842 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2847 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2848 assert_eq!(commitment_spend.input.len(), 2);
2849 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2850 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2851 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2852 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2853 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2854 // we already checked the same situation with A.
2856 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2857 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2858 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2859 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2860 check_closed_broadcast!(nodes[0], true);
2861 check_added_monitors!(nodes[0], 1);
2862 let events = nodes[0].node.get_and_clear_pending_events();
2863 assert_eq!(events.len(), 5);
2864 let mut first_claimed = false;
2865 for event in events {
2867 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2868 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2869 assert!(!first_claimed);
2870 first_claimed = true;
2872 assert_eq!(payment_preimage, our_payment_preimage_2);
2873 assert_eq!(payment_hash, payment_hash_2);
2876 Event::PaymentPathSuccessful { .. } => {},
2877 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2878 _ => panic!("Unexpected event"),
2881 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2884 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2885 // Test that in case of a unilateral close onchain, we detect the state of output and
2886 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2887 // broadcasting the right event to other nodes in payment path.
2888 // A ------------------> B ----------------------> C (timeout)
2889 // B's commitment tx C's commitment tx
2891 // B's HTLC timeout tx B's timeout tx
2893 let chanmon_cfgs = create_chanmon_cfgs(3);
2894 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2895 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2896 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2897 *nodes[0].connect_style.borrow_mut() = connect_style;
2898 *nodes[1].connect_style.borrow_mut() = connect_style;
2899 *nodes[2].connect_style.borrow_mut() = connect_style;
2901 // Create some intial channels
2902 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2903 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2905 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2906 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2907 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2909 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2911 // Broadcast legit commitment tx from C on B's chain
2912 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2913 check_spends!(commitment_tx[0], chan_2.3);
2914 nodes[2].node.fail_htlc_backwards(&payment_hash);
2915 check_added_monitors!(nodes[2], 0);
2916 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2917 check_added_monitors!(nodes[2], 1);
2919 let events = nodes[2].node.get_and_clear_pending_msg_events();
2920 assert_eq!(events.len(), 1);
2922 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, .. } } => {
2923 assert!(update_add_htlcs.is_empty());
2924 assert!(!update_fail_htlcs.is_empty());
2925 assert!(update_fulfill_htlcs.is_empty());
2926 assert!(update_fail_malformed_htlcs.is_empty());
2927 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2929 _ => panic!("Unexpected event"),
2931 mine_transaction(&nodes[2], &commitment_tx[0]);
2932 check_closed_broadcast!(nodes[2], true);
2933 check_added_monitors!(nodes[2], 1);
2934 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2935 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2936 assert_eq!(node_txn.len(), 0);
2938 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2939 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2940 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2941 mine_transaction(&nodes[1], &commitment_tx[0]);
2942 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2945 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2946 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2948 check_spends!(node_txn[2], commitment_tx[0]);
2949 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2951 check_spends!(node_txn[0], chan_2.3);
2952 check_spends!(node_txn[1], node_txn[0]);
2953 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2954 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2956 timeout_tx = node_txn[2].clone();
2960 mine_transaction(&nodes[1], &timeout_tx);
2961 check_added_monitors!(nodes[1], 1);
2962 check_closed_broadcast!(nodes[1], true);
2964 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2966 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 }]);
2967 check_added_monitors!(nodes[1], 1);
2968 let events = nodes[1].node.get_and_clear_pending_msg_events();
2969 assert_eq!(events.len(), 1);
2971 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2972 assert!(update_add_htlcs.is_empty());
2973 assert!(!update_fail_htlcs.is_empty());
2974 assert!(update_fulfill_htlcs.is_empty());
2975 assert!(update_fail_malformed_htlcs.is_empty());
2976 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2978 _ => panic!("Unexpected event"),
2981 // Broadcast legit commitment tx from B on A's chain
2982 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2983 check_spends!(commitment_tx[0], chan_1.3);
2985 mine_transaction(&nodes[0], &commitment_tx[0]);
2986 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2988 check_closed_broadcast!(nodes[0], true);
2989 check_added_monitors!(nodes[0], 1);
2990 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2991 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2992 assert_eq!(node_txn.len(), 1);
2993 check_spends!(node_txn[0], commitment_tx[0]);
2994 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2998 fn test_htlc_on_chain_timeout() {
2999 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3000 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3001 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3005 fn test_simple_commitment_revoked_fail_backward() {
3006 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3007 // and fail backward accordingly.
3009 let chanmon_cfgs = create_chanmon_cfgs(3);
3010 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3011 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3012 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3014 // Create some initial channels
3015 create_announced_chan_between_nodes(&nodes, 0, 1);
3016 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3018 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3019 // Get the will-be-revoked local txn from nodes[2]
3020 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3021 // Revoke the old state
3022 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3024 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3026 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3027 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3028 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3029 check_added_monitors!(nodes[1], 1);
3030 check_closed_broadcast!(nodes[1], true);
3032 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 }]);
3033 check_added_monitors!(nodes[1], 1);
3034 let events = nodes[1].node.get_and_clear_pending_msg_events();
3035 assert_eq!(events.len(), 1);
3037 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, .. } } => {
3038 assert!(update_add_htlcs.is_empty());
3039 assert_eq!(update_fail_htlcs.len(), 1);
3040 assert!(update_fulfill_htlcs.is_empty());
3041 assert!(update_fail_malformed_htlcs.is_empty());
3042 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3044 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3045 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3046 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3048 _ => panic!("Unexpected event"),
3052 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3053 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3054 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3055 // commitment transaction anymore.
3056 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3057 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3058 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3059 // technically disallowed and we should probably handle it reasonably.
3060 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3061 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3063 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3064 // commitment_signed (implying it will be in the latest remote commitment transaction).
3065 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3066 // and once they revoke the previous commitment transaction (allowing us to send a new
3067 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3068 let chanmon_cfgs = create_chanmon_cfgs(3);
3069 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3070 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3071 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3073 // Create some initial channels
3074 create_announced_chan_between_nodes(&nodes, 0, 1);
3075 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3077 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 });
3078 // Get the will-be-revoked local txn from nodes[2]
3079 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3080 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3081 // Revoke the old state
3082 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3084 let value = if use_dust {
3085 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3086 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3087 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3088 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3091 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3092 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3093 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3096 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3097 check_added_monitors!(nodes[2], 1);
3098 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3099 assert!(updates.update_add_htlcs.is_empty());
3100 assert!(updates.update_fulfill_htlcs.is_empty());
3101 assert!(updates.update_fail_malformed_htlcs.is_empty());
3102 assert_eq!(updates.update_fail_htlcs.len(), 1);
3103 assert!(updates.update_fee.is_none());
3104 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3105 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3106 // Drop the last RAA from 3 -> 2
3108 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3109 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3110 check_added_monitors!(nodes[2], 1);
3111 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3112 assert!(updates.update_add_htlcs.is_empty());
3113 assert!(updates.update_fulfill_htlcs.is_empty());
3114 assert!(updates.update_fail_malformed_htlcs.is_empty());
3115 assert_eq!(updates.update_fail_htlcs.len(), 1);
3116 assert!(updates.update_fee.is_none());
3117 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3118 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3119 check_added_monitors!(nodes[1], 1);
3120 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3121 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3122 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3123 check_added_monitors!(nodes[2], 1);
3125 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3126 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3127 check_added_monitors!(nodes[2], 1);
3128 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3129 assert!(updates.update_add_htlcs.is_empty());
3130 assert!(updates.update_fulfill_htlcs.is_empty());
3131 assert!(updates.update_fail_malformed_htlcs.is_empty());
3132 assert_eq!(updates.update_fail_htlcs.len(), 1);
3133 assert!(updates.update_fee.is_none());
3134 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3135 // At this point first_payment_hash has dropped out of the latest two commitment
3136 // transactions that nodes[1] is tracking...
3137 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3138 check_added_monitors!(nodes[1], 1);
3139 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3140 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3141 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3142 check_added_monitors!(nodes[2], 1);
3144 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3145 // on nodes[2]'s RAA.
3146 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3147 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3148 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3149 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3150 check_added_monitors!(nodes[1], 0);
3153 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3154 // One monitor for the new revocation preimage, no second on as we won't generate a new
3155 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3156 check_added_monitors!(nodes[1], 1);
3157 let events = nodes[1].node.get_and_clear_pending_events();
3158 assert_eq!(events.len(), 2);
3160 Event::PendingHTLCsForwardable { .. } => { },
3161 _ => panic!("Unexpected event"),
3164 Event::HTLCHandlingFailed { .. } => { },
3165 _ => panic!("Unexpected event"),
3167 // Deliberately don't process the pending fail-back so they all fail back at once after
3168 // block connection just like the !deliver_bs_raa case
3171 let mut failed_htlcs = HashSet::new();
3172 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3174 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3175 check_added_monitors!(nodes[1], 1);
3176 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3178 let events = nodes[1].node.get_and_clear_pending_events();
3179 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3181 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3182 _ => panic!("Unexepected event"),
3185 Event::PaymentPathFailed { ref payment_hash, .. } => {
3186 assert_eq!(*payment_hash, fourth_payment_hash);
3188 _ => panic!("Unexpected event"),
3191 Event::PaymentFailed { ref payment_hash, .. } => {
3192 assert_eq!(*payment_hash, fourth_payment_hash);
3194 _ => panic!("Unexpected event"),
3197 nodes[1].node.process_pending_htlc_forwards();
3198 check_added_monitors!(nodes[1], 1);
3200 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3201 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3204 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3205 match nodes_2_event {
3206 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, .. } } => {
3207 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3208 assert_eq!(update_add_htlcs.len(), 1);
3209 assert!(update_fulfill_htlcs.is_empty());
3210 assert!(update_fail_htlcs.is_empty());
3211 assert!(update_fail_malformed_htlcs.is_empty());
3213 _ => panic!("Unexpected event"),
3217 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3218 match nodes_2_event {
3219 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3220 assert_eq!(channel_id, chan_2.2);
3221 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3223 _ => panic!("Unexpected event"),
3226 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3227 match nodes_0_event {
3228 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, .. } } => {
3229 assert!(update_add_htlcs.is_empty());
3230 assert_eq!(update_fail_htlcs.len(), 3);
3231 assert!(update_fulfill_htlcs.is_empty());
3232 assert!(update_fail_malformed_htlcs.is_empty());
3233 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3235 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3236 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3237 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3239 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3241 let events = nodes[0].node.get_and_clear_pending_events();
3242 assert_eq!(events.len(), 6);
3244 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3245 assert!(failed_htlcs.insert(payment_hash.0));
3246 // If we delivered B's RAA we got an unknown preimage error, not something
3247 // that we should update our routing table for.
3248 if !deliver_bs_raa {
3249 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3252 _ => panic!("Unexpected event"),
3255 Event::PaymentFailed { ref payment_hash, .. } => {
3256 assert_eq!(*payment_hash, first_payment_hash);
3258 _ => panic!("Unexpected event"),
3261 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3262 assert!(failed_htlcs.insert(payment_hash.0));
3264 _ => panic!("Unexpected event"),
3267 Event::PaymentFailed { ref payment_hash, .. } => {
3268 assert_eq!(*payment_hash, second_payment_hash);
3270 _ => panic!("Unexpected event"),
3273 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3274 assert!(failed_htlcs.insert(payment_hash.0));
3276 _ => panic!("Unexpected event"),
3279 Event::PaymentFailed { ref payment_hash, .. } => {
3280 assert_eq!(*payment_hash, third_payment_hash);
3282 _ => panic!("Unexpected event"),
3285 _ => panic!("Unexpected event"),
3288 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3290 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3291 _ => panic!("Unexpected event"),
3294 assert!(failed_htlcs.contains(&first_payment_hash.0));
3295 assert!(failed_htlcs.contains(&second_payment_hash.0));
3296 assert!(failed_htlcs.contains(&third_payment_hash.0));
3300 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3301 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3302 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3303 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3304 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3308 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3309 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3310 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3311 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3312 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3316 fn fail_backward_pending_htlc_upon_channel_failure() {
3317 let chanmon_cfgs = create_chanmon_cfgs(2);
3318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3320 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3321 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3323 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3325 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3326 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3327 check_added_monitors!(nodes[0], 1);
3329 let payment_event = {
3330 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3331 assert_eq!(events.len(), 1);
3332 SendEvent::from_event(events.remove(0))
3334 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3335 assert_eq!(payment_event.msgs.len(), 1);
3338 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3339 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3341 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3342 check_added_monitors!(nodes[0], 0);
3344 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3347 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3349 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3351 let secp_ctx = Secp256k1::new();
3352 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3353 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3354 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3355 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3356 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3358 // Send a 0-msat update_add_htlc to fail the channel.
3359 let update_add_htlc = msgs::UpdateAddHTLC {
3365 onion_routing_packet,
3367 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3369 let events = nodes[0].node.get_and_clear_pending_events();
3370 assert_eq!(events.len(), 3);
3371 // Check that Alice fails backward the pending HTLC from the second payment.
3373 Event::PaymentPathFailed { payment_hash, .. } => {
3374 assert_eq!(payment_hash, failed_payment_hash);
3376 _ => panic!("Unexpected event"),
3379 Event::PaymentFailed { payment_hash, .. } => {
3380 assert_eq!(payment_hash, failed_payment_hash);
3382 _ => panic!("Unexpected event"),
3385 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3386 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3388 _ => panic!("Unexpected event {:?}", events[1]),
3390 check_closed_broadcast!(nodes[0], true);
3391 check_added_monitors!(nodes[0], 1);
3395 fn test_htlc_ignore_latest_remote_commitment() {
3396 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3397 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3398 let chanmon_cfgs = create_chanmon_cfgs(2);
3399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3401 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3402 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3403 // We rely on the ability to connect a block redundantly, which isn't allowed via
3404 // `chain::Listen`, so we never run the test if we randomly get assigned that
3408 create_announced_chan_between_nodes(&nodes, 0, 1);
3410 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3411 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3412 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3413 check_closed_broadcast!(nodes[0], true);
3414 check_added_monitors!(nodes[0], 1);
3415 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3417 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3418 assert_eq!(node_txn.len(), 3);
3419 assert_eq!(node_txn[0], node_txn[1]);
3421 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3422 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3423 check_closed_broadcast!(nodes[1], true);
3424 check_added_monitors!(nodes[1], 1);
3425 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3427 // Duplicate the connect_block call since this may happen due to other listeners
3428 // registering new transactions
3429 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3433 fn test_force_close_fail_back() {
3434 // Check which HTLCs are failed-backwards on channel force-closure
3435 let chanmon_cfgs = create_chanmon_cfgs(3);
3436 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3437 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3438 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3439 create_announced_chan_between_nodes(&nodes, 0, 1);
3440 create_announced_chan_between_nodes(&nodes, 1, 2);
3442 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3444 let mut payment_event = {
3445 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3446 check_added_monitors!(nodes[0], 1);
3448 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3449 assert_eq!(events.len(), 1);
3450 SendEvent::from_event(events.remove(0))
3453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3454 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3456 expect_pending_htlcs_forwardable!(nodes[1]);
3458 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3459 assert_eq!(events_2.len(), 1);
3460 payment_event = SendEvent::from_event(events_2.remove(0));
3461 assert_eq!(payment_event.msgs.len(), 1);
3463 check_added_monitors!(nodes[1], 1);
3464 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3465 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3466 check_added_monitors!(nodes[2], 1);
3467 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3469 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3470 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3471 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3473 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3474 check_closed_broadcast!(nodes[2], true);
3475 check_added_monitors!(nodes[2], 1);
3476 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3478 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3479 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3480 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3481 // back to nodes[1] upon timeout otherwise.
3482 assert_eq!(node_txn.len(), 1);
3486 mine_transaction(&nodes[1], &tx);
3488 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3489 check_closed_broadcast!(nodes[1], true);
3490 check_added_monitors!(nodes[1], 1);
3491 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3493 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3495 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3496 .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);
3498 mine_transaction(&nodes[2], &tx);
3499 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3500 assert_eq!(node_txn.len(), 1);
3501 assert_eq!(node_txn[0].input.len(), 1);
3502 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3503 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3504 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3506 check_spends!(node_txn[0], tx);
3510 fn test_dup_events_on_peer_disconnect() {
3511 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3512 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3513 // as we used to generate the event immediately upon receipt of the payment preimage in the
3514 // update_fulfill_htlc message.
3516 let chanmon_cfgs = create_chanmon_cfgs(2);
3517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3519 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3520 create_announced_chan_between_nodes(&nodes, 0, 1);
3522 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3524 nodes[1].node.claim_funds(payment_preimage);
3525 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3526 check_added_monitors!(nodes[1], 1);
3527 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3528 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3529 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3531 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3532 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3534 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3535 expect_payment_path_successful!(nodes[0]);
3539 fn test_peer_disconnected_before_funding_broadcasted() {
3540 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3541 // before the funding transaction has been broadcasted.
3542 let chanmon_cfgs = create_chanmon_cfgs(2);
3543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3545 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3547 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3548 // broadcasted, even though it's created by `nodes[0]`.
3549 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();
3550 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3551 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3552 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3553 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3555 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3556 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3558 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3560 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3561 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3563 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3564 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3567 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3570 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3571 // disconnected before the funding transaction was broadcasted.
3572 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3573 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3575 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3576 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3580 fn test_simple_peer_disconnect() {
3581 // Test that we can reconnect when there are no lost messages
3582 let chanmon_cfgs = create_chanmon_cfgs(3);
3583 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3584 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3585 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3586 create_announced_chan_between_nodes(&nodes, 0, 1);
3587 create_announced_chan_between_nodes(&nodes, 1, 2);
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3591 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3594 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3595 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3596 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3598 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3599 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3600 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3602 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3603 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3604 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3605 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3607 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3608 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3610 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3611 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3613 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3615 let events = nodes[0].node.get_and_clear_pending_events();
3616 assert_eq!(events.len(), 4);
3618 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3619 assert_eq!(payment_preimage, payment_preimage_3);
3620 assert_eq!(payment_hash, payment_hash_3);
3622 _ => panic!("Unexpected event"),
3625 Event::PaymentPathSuccessful { .. } => {},
3626 _ => panic!("Unexpected event"),
3629 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3630 assert_eq!(payment_hash, payment_hash_5);
3631 assert!(payment_failed_permanently);
3633 _ => panic!("Unexpected event"),
3636 Event::PaymentFailed { payment_hash, .. } => {
3637 assert_eq!(payment_hash, payment_hash_5);
3639 _ => panic!("Unexpected event"),
3643 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3644 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3647 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3648 // Test that we can reconnect when in-flight HTLC updates get dropped
3649 let chanmon_cfgs = create_chanmon_cfgs(2);
3650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3652 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3654 let mut as_channel_ready = None;
3655 let channel_id = if messages_delivered == 0 {
3656 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3657 as_channel_ready = Some(channel_ready);
3658 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3659 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3660 // it before the channel_reestablish message.
3663 create_announced_chan_between_nodes(&nodes, 0, 1).2
3666 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3668 let payment_event = {
3669 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3670 check_added_monitors!(nodes[0], 1);
3672 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3673 assert_eq!(events.len(), 1);
3674 SendEvent::from_event(events.remove(0))
3676 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3678 if messages_delivered < 2 {
3679 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3681 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3682 if messages_delivered >= 3 {
3683 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3684 check_added_monitors!(nodes[1], 1);
3685 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3687 if messages_delivered >= 4 {
3688 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3689 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3690 check_added_monitors!(nodes[0], 1);
3692 if messages_delivered >= 5 {
3693 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3694 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3695 // No commitment_signed so get_event_msg's assert(len == 1) passes
3696 check_added_monitors!(nodes[0], 1);
3698 if messages_delivered >= 6 {
3699 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3700 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3701 check_added_monitors!(nodes[1], 1);
3708 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3709 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3710 if messages_delivered < 3 {
3711 if simulate_broken_lnd {
3712 // lnd has a long-standing bug where they send a channel_ready prior to a
3713 // channel_reestablish if you reconnect prior to channel_ready time.
3715 // Here we simulate that behavior, delivering a channel_ready immediately on
3716 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3717 // in `reconnect_nodes` but we currently don't fail based on that.
3719 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3720 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3722 // Even if the channel_ready messages get exchanged, as long as nothing further was
3723 // received on either side, both sides will need to resend them.
3724 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3725 } else if messages_delivered == 3 {
3726 // nodes[0] still wants its RAA + commitment_signed
3727 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3728 } else if messages_delivered == 4 {
3729 // nodes[0] still wants its commitment_signed
3730 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3731 } else if messages_delivered == 5 {
3732 // nodes[1] still wants its final RAA
3733 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3734 } else if messages_delivered == 6 {
3735 // Everything was delivered...
3736 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3739 let events_1 = nodes[1].node.get_and_clear_pending_events();
3740 if messages_delivered == 0 {
3741 assert_eq!(events_1.len(), 2);
3743 Event::ChannelReady { .. } => { },
3744 _ => panic!("Unexpected event"),
3747 Event::PendingHTLCsForwardable { .. } => { },
3748 _ => panic!("Unexpected event"),
3751 assert_eq!(events_1.len(), 1);
3753 Event::PendingHTLCsForwardable { .. } => { },
3754 _ => panic!("Unexpected event"),
3758 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3759 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3760 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3762 nodes[1].node.process_pending_htlc_forwards();
3764 let events_2 = nodes[1].node.get_and_clear_pending_events();
3765 assert_eq!(events_2.len(), 1);
3767 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3768 assert_eq!(payment_hash_1, *payment_hash);
3769 assert_eq!(amount_msat, 1_000_000);
3770 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3771 assert_eq!(via_channel_id, Some(channel_id));
3773 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3774 assert!(payment_preimage.is_none());
3775 assert_eq!(payment_secret_1, *payment_secret);
3777 _ => panic!("expected PaymentPurpose::InvoicePayment")
3780 _ => panic!("Unexpected event"),
3783 nodes[1].node.claim_funds(payment_preimage_1);
3784 check_added_monitors!(nodes[1], 1);
3785 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3787 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3788 assert_eq!(events_3.len(), 1);
3789 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3790 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3791 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3792 assert!(updates.update_add_htlcs.is_empty());
3793 assert!(updates.update_fail_htlcs.is_empty());
3794 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3795 assert!(updates.update_fail_malformed_htlcs.is_empty());
3796 assert!(updates.update_fee.is_none());
3797 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3799 _ => panic!("Unexpected event"),
3802 if messages_delivered >= 1 {
3803 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3805 let events_4 = nodes[0].node.get_and_clear_pending_events();
3806 assert_eq!(events_4.len(), 1);
3808 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3809 assert_eq!(payment_preimage_1, *payment_preimage);
3810 assert_eq!(payment_hash_1, *payment_hash);
3812 _ => panic!("Unexpected event"),
3815 if messages_delivered >= 2 {
3816 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3817 check_added_monitors!(nodes[0], 1);
3818 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3820 if messages_delivered >= 3 {
3821 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3822 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3823 check_added_monitors!(nodes[1], 1);
3825 if messages_delivered >= 4 {
3826 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3827 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3828 // No commitment_signed so get_event_msg's assert(len == 1) passes
3829 check_added_monitors!(nodes[1], 1);
3831 if messages_delivered >= 5 {
3832 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3833 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3834 check_added_monitors!(nodes[0], 1);
3841 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3842 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3843 if messages_delivered < 2 {
3844 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3845 if messages_delivered < 1 {
3846 expect_payment_sent!(nodes[0], payment_preimage_1);
3848 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3850 } else if messages_delivered == 2 {
3851 // nodes[0] still wants its RAA + commitment_signed
3852 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3853 } else if messages_delivered == 3 {
3854 // nodes[0] still wants its commitment_signed
3855 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3856 } else if messages_delivered == 4 {
3857 // nodes[1] still wants its final RAA
3858 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3859 } else if messages_delivered == 5 {
3860 // Everything was delivered...
3861 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3864 if messages_delivered == 1 || messages_delivered == 2 {
3865 expect_payment_path_successful!(nodes[0]);
3867 if messages_delivered <= 5 {
3868 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3869 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3871 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3873 if messages_delivered > 2 {
3874 expect_payment_path_successful!(nodes[0]);
3877 // Channel should still work fine...
3878 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3879 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3880 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3884 fn test_drop_messages_peer_disconnect_a() {
3885 do_test_drop_messages_peer_disconnect(0, true);
3886 do_test_drop_messages_peer_disconnect(0, false);
3887 do_test_drop_messages_peer_disconnect(1, false);
3888 do_test_drop_messages_peer_disconnect(2, false);
3892 fn test_drop_messages_peer_disconnect_b() {
3893 do_test_drop_messages_peer_disconnect(3, false);
3894 do_test_drop_messages_peer_disconnect(4, false);
3895 do_test_drop_messages_peer_disconnect(5, false);
3896 do_test_drop_messages_peer_disconnect(6, false);
3900 fn test_channel_ready_without_best_block_updated() {
3901 // Previously, if we were offline when a funding transaction was locked in, and then we came
3902 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3903 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3904 // channel_ready immediately instead.
3905 let chanmon_cfgs = create_chanmon_cfgs(2);
3906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3908 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3909 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3911 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3913 let conf_height = nodes[0].best_block_info().1 + 1;
3914 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3915 let block_txn = [funding_tx];
3916 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3917 let conf_block_header = nodes[0].get_block_header(conf_height);
3918 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3920 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3921 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3922 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3926 fn test_drop_messages_peer_disconnect_dual_htlc() {
3927 // Test that we can handle reconnecting when both sides of a channel have pending
3928 // commitment_updates when we disconnect.
3929 let chanmon_cfgs = create_chanmon_cfgs(2);
3930 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3931 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3932 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3933 create_announced_chan_between_nodes(&nodes, 0, 1);
3935 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3937 // Now try to send a second payment which will fail to send
3938 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3939 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3940 check_added_monitors!(nodes[0], 1);
3942 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3943 assert_eq!(events_1.len(), 1);
3945 MessageSendEvent::UpdateHTLCs { .. } => {},
3946 _ => panic!("Unexpected event"),
3949 nodes[1].node.claim_funds(payment_preimage_1);
3950 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3951 check_added_monitors!(nodes[1], 1);
3953 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3954 assert_eq!(events_2.len(), 1);
3956 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 } } => {
3957 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3958 assert!(update_add_htlcs.is_empty());
3959 assert_eq!(update_fulfill_htlcs.len(), 1);
3960 assert!(update_fail_htlcs.is_empty());
3961 assert!(update_fail_malformed_htlcs.is_empty());
3962 assert!(update_fee.is_none());
3964 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3965 let events_3 = nodes[0].node.get_and_clear_pending_events();
3966 assert_eq!(events_3.len(), 1);
3968 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3969 assert_eq!(*payment_preimage, payment_preimage_1);
3970 assert_eq!(*payment_hash, payment_hash_1);
3972 _ => panic!("Unexpected event"),
3975 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3976 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3977 // No commitment_signed so get_event_msg's assert(len == 1) passes
3978 check_added_monitors!(nodes[0], 1);
3980 _ => panic!("Unexpected event"),
3983 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3984 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3986 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();
3987 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3988 assert_eq!(reestablish_1.len(), 1);
3989 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();
3990 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3991 assert_eq!(reestablish_2.len(), 1);
3993 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3994 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3995 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3996 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3998 assert!(as_resp.0.is_none());
3999 assert!(bs_resp.0.is_none());
4001 assert!(bs_resp.1.is_none());
4002 assert!(bs_resp.2.is_none());
4004 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4006 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4007 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4008 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4009 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4010 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4011 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4012 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4013 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4014 // No commitment_signed so get_event_msg's assert(len == 1) passes
4015 check_added_monitors!(nodes[1], 1);
4017 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4018 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4019 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4020 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4021 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4022 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4023 assert!(bs_second_commitment_signed.update_fee.is_none());
4024 check_added_monitors!(nodes[1], 1);
4026 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4027 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4028 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4029 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4030 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4031 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4032 assert!(as_commitment_signed.update_fee.is_none());
4033 check_added_monitors!(nodes[0], 1);
4035 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4036 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4037 // No commitment_signed so get_event_msg's assert(len == 1) passes
4038 check_added_monitors!(nodes[0], 1);
4040 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4041 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4042 // No commitment_signed so get_event_msg's assert(len == 1) passes
4043 check_added_monitors!(nodes[1], 1);
4045 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4046 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4047 check_added_monitors!(nodes[1], 1);
4049 expect_pending_htlcs_forwardable!(nodes[1]);
4051 let events_5 = nodes[1].node.get_and_clear_pending_events();
4052 assert_eq!(events_5.len(), 1);
4054 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4055 assert_eq!(payment_hash_2, *payment_hash);
4057 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4058 assert!(payment_preimage.is_none());
4059 assert_eq!(payment_secret_2, *payment_secret);
4061 _ => panic!("expected PaymentPurpose::InvoicePayment")
4064 _ => panic!("Unexpected event"),
4067 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4068 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4069 check_added_monitors!(nodes[0], 1);
4071 expect_payment_path_successful!(nodes[0]);
4072 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4075 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4076 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4077 // to avoid our counterparty failing the channel.
4078 let chanmon_cfgs = create_chanmon_cfgs(2);
4079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4081 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4083 create_announced_chan_between_nodes(&nodes, 0, 1);
4085 let our_payment_hash = if send_partial_mpp {
4086 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4087 // Use the utility function send_payment_along_path to send the payment with MPP data which
4088 // indicates there are more HTLCs coming.
4089 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.
4090 let payment_id = PaymentId([42; 32]);
4091 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4092 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();
4093 check_added_monitors!(nodes[0], 1);
4094 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4095 assert_eq!(events.len(), 1);
4096 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4097 // hop should *not* yet generate any PaymentClaimable event(s).
4098 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4101 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4104 let mut block = Block {
4105 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4108 connect_block(&nodes[0], &block);
4109 connect_block(&nodes[1], &block);
4110 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4111 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4112 block.header.prev_blockhash = block.block_hash();
4113 connect_block(&nodes[0], &block);
4114 connect_block(&nodes[1], &block);
4117 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4119 check_added_monitors!(nodes[1], 1);
4120 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4121 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4122 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4123 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4124 assert!(htlc_timeout_updates.update_fee.is_none());
4126 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4127 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4128 // 100_000 msat as u64, followed by the height at which we failed back above
4129 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4130 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4131 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4135 fn test_htlc_timeout() {
4136 do_test_htlc_timeout(true);
4137 do_test_htlc_timeout(false);
4140 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4141 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4142 let chanmon_cfgs = create_chanmon_cfgs(3);
4143 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4144 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4145 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4146 create_announced_chan_between_nodes(&nodes, 0, 1);
4147 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4149 // Make sure all nodes are at the same starting height
4150 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4151 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4152 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4154 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4155 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4157 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4159 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4160 check_added_monitors!(nodes[1], 1);
4162 // Now attempt to route a second payment, which should be placed in the holding cell
4163 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4164 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4165 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4167 check_added_monitors!(nodes[0], 1);
4168 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4169 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4170 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4171 expect_pending_htlcs_forwardable!(nodes[1]);
4173 check_added_monitors!(nodes[1], 0);
4175 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4176 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4177 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4178 connect_blocks(&nodes[1], 1);
4181 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 }]);
4182 check_added_monitors!(nodes[1], 1);
4183 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4184 assert_eq!(fail_commit.len(), 1);
4185 match fail_commit[0] {
4186 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4187 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4188 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4190 _ => unreachable!(),
4192 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4194 expect_payment_failed!(nodes[1], second_payment_hash, false);
4199 fn test_holding_cell_htlc_add_timeouts() {
4200 do_test_holding_cell_htlc_add_timeouts(false);
4201 do_test_holding_cell_htlc_add_timeouts(true);
4204 macro_rules! check_spendable_outputs {
4205 ($node: expr, $keysinterface: expr) => {
4207 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4208 let mut txn = Vec::new();
4209 let mut all_outputs = Vec::new();
4210 let secp_ctx = Secp256k1::new();
4211 for event in events.drain(..) {
4213 Event::SpendableOutputs { mut outputs } => {
4214 for outp in outputs.drain(..) {
4215 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4216 all_outputs.push(outp);
4219 _ => panic!("Unexpected event"),
4222 if all_outputs.len() > 1 {
4223 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) {
4233 fn test_claim_sizeable_push_msat() {
4234 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4235 let chanmon_cfgs = create_chanmon_cfgs(2);
4236 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4237 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4238 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4240 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4241 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4242 check_closed_broadcast!(nodes[1], true);
4243 check_added_monitors!(nodes[1], 1);
4244 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4245 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4246 assert_eq!(node_txn.len(), 1);
4247 check_spends!(node_txn[0], chan.3);
4248 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
4250 mine_transaction(&nodes[1], &node_txn[0]);
4251 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4253 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4254 assert_eq!(spend_txn.len(), 1);
4255 assert_eq!(spend_txn[0].input.len(), 1);
4256 check_spends!(spend_txn[0], node_txn[0]);
4257 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4261 fn test_claim_on_remote_sizeable_push_msat() {
4262 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4263 // to_remote output is encumbered by a P2WPKH
4264 let chanmon_cfgs = create_chanmon_cfgs(2);
4265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4269 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4270 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4271 check_closed_broadcast!(nodes[0], true);
4272 check_added_monitors!(nodes[0], 1);
4273 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4275 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4276 assert_eq!(node_txn.len(), 1);
4277 check_spends!(node_txn[0], chan.3);
4278 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
4280 mine_transaction(&nodes[1], &node_txn[0]);
4281 check_closed_broadcast!(nodes[1], true);
4282 check_added_monitors!(nodes[1], 1);
4283 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4284 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4286 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4287 assert_eq!(spend_txn.len(), 1);
4288 check_spends!(spend_txn[0], node_txn[0]);
4292 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4293 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4294 // to_remote output is encumbered by a P2WPKH
4296 let chanmon_cfgs = create_chanmon_cfgs(2);
4297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4299 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4301 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4302 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4303 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4304 assert_eq!(revoked_local_txn[0].input.len(), 1);
4305 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4307 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4308 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4309 check_closed_broadcast!(nodes[1], true);
4310 check_added_monitors!(nodes[1], 1);
4311 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4313 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4314 mine_transaction(&nodes[1], &node_txn[0]);
4315 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4317 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4318 assert_eq!(spend_txn.len(), 3);
4319 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4320 check_spends!(spend_txn[1], node_txn[0]);
4321 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4325 fn test_static_spendable_outputs_preimage_tx() {
4326 let chanmon_cfgs = create_chanmon_cfgs(2);
4327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4329 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4331 // Create some initial channels
4332 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4334 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4336 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4337 assert_eq!(commitment_tx[0].input.len(), 1);
4338 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4340 // Settle A's commitment tx on B's chain
4341 nodes[1].node.claim_funds(payment_preimage);
4342 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4343 check_added_monitors!(nodes[1], 1);
4344 mine_transaction(&nodes[1], &commitment_tx[0]);
4345 check_added_monitors!(nodes[1], 1);
4346 let events = nodes[1].node.get_and_clear_pending_msg_events();
4348 MessageSendEvent::UpdateHTLCs { .. } => {},
4349 _ => panic!("Unexpected event"),
4352 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4353 _ => panic!("Unexepected event"),
4356 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4357 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4358 assert_eq!(node_txn.len(), 1);
4359 check_spends!(node_txn[0], commitment_tx[0]);
4360 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4362 mine_transaction(&nodes[1], &node_txn[0]);
4363 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4364 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4366 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4367 assert_eq!(spend_txn.len(), 1);
4368 check_spends!(spend_txn[0], node_txn[0]);
4372 fn test_static_spendable_outputs_timeout_tx() {
4373 let chanmon_cfgs = create_chanmon_cfgs(2);
4374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4378 // Create some initial channels
4379 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4381 // Rebalance the network a bit by relaying one payment through all the channels ...
4382 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4384 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4386 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4387 assert_eq!(commitment_tx[0].input.len(), 1);
4388 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4390 // Settle A's commitment tx on B' chain
4391 mine_transaction(&nodes[1], &commitment_tx[0]);
4392 check_added_monitors!(nodes[1], 1);
4393 let events = nodes[1].node.get_and_clear_pending_msg_events();
4395 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4396 _ => panic!("Unexpected event"),
4398 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4400 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4401 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4402 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4403 check_spends!(node_txn[0], commitment_tx[0].clone());
4404 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4406 mine_transaction(&nodes[1], &node_txn[0]);
4407 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4408 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4409 expect_payment_failed!(nodes[1], our_payment_hash, false);
4411 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4412 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4413 check_spends!(spend_txn[0], commitment_tx[0]);
4414 check_spends!(spend_txn[1], node_txn[0]);
4415 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4419 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4420 let chanmon_cfgs = create_chanmon_cfgs(2);
4421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4423 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4425 // Create some initial channels
4426 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4428 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4429 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4430 assert_eq!(revoked_local_txn[0].input.len(), 1);
4431 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4433 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4435 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4436 check_closed_broadcast!(nodes[1], true);
4437 check_added_monitors!(nodes[1], 1);
4438 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4440 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4441 assert_eq!(node_txn.len(), 1);
4442 assert_eq!(node_txn[0].input.len(), 2);
4443 check_spends!(node_txn[0], revoked_local_txn[0]);
4445 mine_transaction(&nodes[1], &node_txn[0]);
4446 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4448 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4449 assert_eq!(spend_txn.len(), 1);
4450 check_spends!(spend_txn[0], node_txn[0]);
4454 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4455 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4456 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4457 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4458 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4459 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4461 // Create some initial channels
4462 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4464 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4465 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4466 assert_eq!(revoked_local_txn[0].input.len(), 1);
4467 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4469 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4471 // A will generate HTLC-Timeout from revoked commitment tx
4472 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4473 check_closed_broadcast!(nodes[0], true);
4474 check_added_monitors!(nodes[0], 1);
4475 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4476 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4478 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4479 assert_eq!(revoked_htlc_txn.len(), 1);
4480 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4481 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4482 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4483 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4485 // B will generate justice tx from A's revoked commitment/HTLC tx
4486 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4487 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4488 check_closed_broadcast!(nodes[1], true);
4489 check_added_monitors!(nodes[1], 1);
4490 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4492 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4493 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4494 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4495 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4496 // transactions next...
4497 assert_eq!(node_txn[0].input.len(), 3);
4498 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4500 assert_eq!(node_txn[1].input.len(), 2);
4501 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4502 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4503 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4505 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4506 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4509 mine_transaction(&nodes[1], &node_txn[1]);
4510 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4512 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4513 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4514 assert_eq!(spend_txn.len(), 1);
4515 assert_eq!(spend_txn[0].input.len(), 1);
4516 check_spends!(spend_txn[0], node_txn[1]);
4520 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4521 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4522 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4525 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4527 // Create some initial channels
4528 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4530 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4531 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4532 assert_eq!(revoked_local_txn[0].input.len(), 1);
4533 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4535 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4536 assert_eq!(revoked_local_txn[0].output.len(), 2);
4538 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4540 // B will generate HTLC-Success from revoked commitment tx
4541 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4542 check_closed_broadcast!(nodes[1], true);
4543 check_added_monitors!(nodes[1], 1);
4544 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4545 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4547 assert_eq!(revoked_htlc_txn.len(), 1);
4548 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4549 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4550 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4552 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4553 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4554 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4556 // A will generate justice tx from B's revoked commitment/HTLC tx
4557 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4558 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4559 check_closed_broadcast!(nodes[0], true);
4560 check_added_monitors!(nodes[0], 1);
4561 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4563 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4564 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4566 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4567 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4568 // transactions next...
4569 assert_eq!(node_txn[0].input.len(), 2);
4570 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4571 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4572 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4574 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4575 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4578 assert_eq!(node_txn[1].input.len(), 1);
4579 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4581 mine_transaction(&nodes[0], &node_txn[1]);
4582 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4584 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4585 // didn't try to generate any new transactions.
4587 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4588 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4589 assert_eq!(spend_txn.len(), 3);
4590 assert_eq!(spend_txn[0].input.len(), 1);
4591 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4592 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4593 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4594 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4598 fn test_onchain_to_onchain_claim() {
4599 // Test that in case of channel closure, we detect the state of output and claim HTLC
4600 // on downstream peer's remote commitment tx.
4601 // First, have C claim an HTLC against its own latest commitment transaction.
4602 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4604 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4607 let chanmon_cfgs = create_chanmon_cfgs(3);
4608 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4609 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4610 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4612 // Create some initial channels
4613 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4614 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4616 // Ensure all nodes are at the same height
4617 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4618 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4619 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4620 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4622 // Rebalance the network a bit by relaying one payment through all the channels ...
4623 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4624 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4626 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4627 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4628 check_spends!(commitment_tx[0], chan_2.3);
4629 nodes[2].node.claim_funds(payment_preimage);
4630 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4631 check_added_monitors!(nodes[2], 1);
4632 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4633 assert!(updates.update_add_htlcs.is_empty());
4634 assert!(updates.update_fail_htlcs.is_empty());
4635 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4636 assert!(updates.update_fail_malformed_htlcs.is_empty());
4638 mine_transaction(&nodes[2], &commitment_tx[0]);
4639 check_closed_broadcast!(nodes[2], true);
4640 check_added_monitors!(nodes[2], 1);
4641 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4643 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4644 assert_eq!(c_txn.len(), 1);
4645 check_spends!(c_txn[0], commitment_tx[0]);
4646 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4647 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4648 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4650 // 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
4651 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4652 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4653 check_added_monitors!(nodes[1], 1);
4654 let events = nodes[1].node.get_and_clear_pending_events();
4655 assert_eq!(events.len(), 2);
4657 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4658 _ => panic!("Unexpected event"),
4661 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4662 assert_eq!(fee_earned_msat, Some(1000));
4663 assert_eq!(prev_channel_id, Some(chan_1.2));
4664 assert_eq!(claim_from_onchain_tx, true);
4665 assert_eq!(next_channel_id, Some(chan_2.2));
4666 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4668 _ => panic!("Unexpected event"),
4670 check_added_monitors!(nodes[1], 1);
4671 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4672 assert_eq!(msg_events.len(), 3);
4673 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4674 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4676 match nodes_2_event {
4677 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4678 _ => panic!("Unexpected event"),
4681 match nodes_0_event {
4682 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, .. } } => {
4683 assert!(update_add_htlcs.is_empty());
4684 assert!(update_fail_htlcs.is_empty());
4685 assert_eq!(update_fulfill_htlcs.len(), 1);
4686 assert!(update_fail_malformed_htlcs.is_empty());
4687 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4689 _ => panic!("Unexpected event"),
4692 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4693 match msg_events[0] {
4694 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4695 _ => panic!("Unexpected event"),
4698 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4699 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4700 mine_transaction(&nodes[1], &commitment_tx[0]);
4701 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4702 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4703 // ChannelMonitor: HTLC-Success tx
4704 assert_eq!(b_txn.len(), 1);
4705 check_spends!(b_txn[0], commitment_tx[0]);
4706 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4707 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4708 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4710 check_closed_broadcast!(nodes[1], true);
4711 check_added_monitors!(nodes[1], 1);
4715 fn test_duplicate_payment_hash_one_failure_one_success() {
4716 // Topology : A --> B --> C --> D
4717 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4718 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4719 // we forward one of the payments onwards to D.
4720 let chanmon_cfgs = create_chanmon_cfgs(4);
4721 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4722 // When this test was written, the default base fee floated based on the HTLC count.
4723 // It is now fixed, so we simply set the fee to the expected value here.
4724 let mut config = test_default_channel_config();
4725 config.channel_config.forwarding_fee_base_msat = 196;
4726 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4727 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4728 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4730 create_announced_chan_between_nodes(&nodes, 0, 1);
4731 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4732 create_announced_chan_between_nodes(&nodes, 2, 3);
4734 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4735 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4736 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4737 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4738 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4740 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4742 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4743 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4744 // script push size limit so that the below script length checks match
4745 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4746 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4747 .with_features(nodes[3].node.invoice_features());
4748 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4749 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4751 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4752 assert_eq!(commitment_txn[0].input.len(), 1);
4753 check_spends!(commitment_txn[0], chan_2.3);
4755 mine_transaction(&nodes[1], &commitment_txn[0]);
4756 check_closed_broadcast!(nodes[1], true);
4757 check_added_monitors!(nodes[1], 1);
4758 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4759 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4761 let htlc_timeout_tx;
4762 { // Extract one of the two HTLC-Timeout transaction
4763 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4764 // ChannelMonitor: timeout tx * 2-or-3
4765 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4767 check_spends!(node_txn[0], commitment_txn[0]);
4768 assert_eq!(node_txn[0].input.len(), 1);
4769 assert_eq!(node_txn[0].output.len(), 1);
4771 if node_txn.len() > 2 {
4772 check_spends!(node_txn[1], commitment_txn[0]);
4773 assert_eq!(node_txn[1].input.len(), 1);
4774 assert_eq!(node_txn[1].output.len(), 1);
4775 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4777 check_spends!(node_txn[2], commitment_txn[0]);
4778 assert_eq!(node_txn[2].input.len(), 1);
4779 assert_eq!(node_txn[2].output.len(), 1);
4780 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4782 check_spends!(node_txn[1], commitment_txn[0]);
4783 assert_eq!(node_txn[1].input.len(), 1);
4784 assert_eq!(node_txn[1].output.len(), 1);
4785 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4788 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4789 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4790 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4791 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4792 if node_txn.len() > 2 {
4793 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4794 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4796 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4800 nodes[2].node.claim_funds(our_payment_preimage);
4801 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4803 mine_transaction(&nodes[2], &commitment_txn[0]);
4804 check_added_monitors!(nodes[2], 2);
4805 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4806 let events = nodes[2].node.get_and_clear_pending_msg_events();
4808 MessageSendEvent::UpdateHTLCs { .. } => {},
4809 _ => panic!("Unexpected event"),
4812 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4813 _ => panic!("Unexepected event"),
4815 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4816 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4817 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4818 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4819 assert_eq!(htlc_success_txn[0].input.len(), 1);
4820 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4821 assert_eq!(htlc_success_txn[1].input.len(), 1);
4822 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4823 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4824 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4826 mine_transaction(&nodes[1], &htlc_timeout_tx);
4827 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4828 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 }]);
4829 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4830 assert!(htlc_updates.update_add_htlcs.is_empty());
4831 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4832 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4833 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4834 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4835 check_added_monitors!(nodes[1], 1);
4837 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4838 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4840 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4842 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4844 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4845 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4846 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4847 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4848 assert!(updates.update_add_htlcs.is_empty());
4849 assert!(updates.update_fail_htlcs.is_empty());
4850 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4851 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4852 assert!(updates.update_fail_malformed_htlcs.is_empty());
4853 check_added_monitors!(nodes[1], 1);
4855 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4856 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4858 let events = nodes[0].node.get_and_clear_pending_events();
4860 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4861 assert_eq!(*payment_preimage, our_payment_preimage);
4862 assert_eq!(*payment_hash, duplicate_payment_hash);
4864 _ => panic!("Unexpected event"),
4869 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4870 let chanmon_cfgs = create_chanmon_cfgs(2);
4871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4873 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4875 // Create some initial channels
4876 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4878 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4879 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4880 assert_eq!(local_txn.len(), 1);
4881 assert_eq!(local_txn[0].input.len(), 1);
4882 check_spends!(local_txn[0], chan_1.3);
4884 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4885 nodes[1].node.claim_funds(payment_preimage);
4886 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4887 check_added_monitors!(nodes[1], 1);
4889 mine_transaction(&nodes[1], &local_txn[0]);
4890 check_added_monitors!(nodes[1], 1);
4891 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4892 let events = nodes[1].node.get_and_clear_pending_msg_events();
4894 MessageSendEvent::UpdateHTLCs { .. } => {},
4895 _ => panic!("Unexpected event"),
4898 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4899 _ => panic!("Unexepected event"),
4902 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4903 assert_eq!(node_txn.len(), 1);
4904 assert_eq!(node_txn[0].input.len(), 1);
4905 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4906 check_spends!(node_txn[0], local_txn[0]);
4910 mine_transaction(&nodes[1], &node_tx);
4911 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4913 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4914 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4915 assert_eq!(spend_txn.len(), 1);
4916 assert_eq!(spend_txn[0].input.len(), 1);
4917 check_spends!(spend_txn[0], node_tx);
4918 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4921 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4922 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4923 // unrevoked commitment transaction.
4924 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4925 // a remote RAA before they could be failed backwards (and combinations thereof).
4926 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4927 // use the same payment hashes.
4928 // Thus, we use a six-node network:
4933 // And test where C fails back to A/B when D announces its latest commitment transaction
4934 let chanmon_cfgs = create_chanmon_cfgs(6);
4935 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4936 // When this test was written, the default base fee floated based on the HTLC count.
4937 // It is now fixed, so we simply set the fee to the expected value here.
4938 let mut config = test_default_channel_config();
4939 config.channel_config.forwarding_fee_base_msat = 196;
4940 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4941 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4942 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4944 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4945 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4946 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4947 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4948 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4950 // Rebalance and check output sanity...
4951 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4952 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4953 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4955 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4956 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4958 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
4960 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
4961 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4963 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
4965 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
4967 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4969 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4970 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4972 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());
4974 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());
4977 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4979 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4980 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
4983 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
4985 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4986 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());
4988 // Double-check that six of the new HTLC were added
4989 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4990 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4991 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4992 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4994 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4995 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4996 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4997 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4998 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4999 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5000 check_added_monitors!(nodes[4], 0);
5002 let failed_destinations = vec![
5003 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5004 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5005 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5006 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5008 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5009 check_added_monitors!(nodes[4], 1);
5011 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5012 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5013 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5014 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5015 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5016 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5018 // Fail 3rd below-dust and 7th above-dust HTLCs
5019 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5020 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5021 check_added_monitors!(nodes[5], 0);
5023 let failed_destinations_2 = vec![
5024 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5025 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5027 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5028 check_added_monitors!(nodes[5], 1);
5030 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5031 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5032 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5033 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5035 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5037 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5038 let failed_destinations_3 = vec![
5039 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5040 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5041 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5042 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5043 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5044 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5046 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5047 check_added_monitors!(nodes[3], 1);
5048 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5049 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5050 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5051 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5052 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5053 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5054 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5055 if deliver_last_raa {
5056 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5058 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5061 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5062 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5063 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5064 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5066 // We now broadcast the latest commitment transaction, which *should* result in failures for
5067 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5068 // the non-broadcast above-dust HTLCs.
5070 // Alternatively, we may broadcast the previous commitment transaction, which should only
5071 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5072 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5074 if announce_latest {
5075 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5077 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5079 let events = nodes[2].node.get_and_clear_pending_events();
5080 let close_event = if deliver_last_raa {
5081 assert_eq!(events.len(), 2 + 6);
5082 events.last().clone().unwrap()
5084 assert_eq!(events.len(), 1);
5085 events.last().clone().unwrap()
5088 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5089 _ => panic!("Unexpected event"),
5092 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5093 check_closed_broadcast!(nodes[2], true);
5094 if deliver_last_raa {
5095 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5097 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();
5098 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5100 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5101 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5103 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5106 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5108 check_added_monitors!(nodes[2], 3);
5110 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5111 assert_eq!(cs_msgs.len(), 2);
5112 let mut a_done = false;
5113 for msg in cs_msgs {
5115 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5116 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5117 // should be failed-backwards here.
5118 let target = if *node_id == nodes[0].node.get_our_node_id() {
5119 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5120 for htlc in &updates.update_fail_htlcs {
5121 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 });
5123 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5128 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5129 for htlc in &updates.update_fail_htlcs {
5130 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5132 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5133 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5136 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5137 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5138 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5139 if announce_latest {
5140 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5141 if *node_id == nodes[0].node.get_our_node_id() {
5142 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5145 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5147 _ => panic!("Unexpected event"),
5151 let as_events = nodes[0].node.get_and_clear_pending_events();
5152 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5153 let mut as_failds = HashSet::new();
5154 let mut as_updates = 0;
5155 for event in as_events.iter() {
5156 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5157 assert!(as_failds.insert(*payment_hash));
5158 if *payment_hash != payment_hash_2 {
5159 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5161 assert!(!payment_failed_permanently);
5163 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5166 } else if let &Event::PaymentFailed { .. } = event {
5167 } else { panic!("Unexpected event"); }
5169 assert!(as_failds.contains(&payment_hash_1));
5170 assert!(as_failds.contains(&payment_hash_2));
5171 if announce_latest {
5172 assert!(as_failds.contains(&payment_hash_3));
5173 assert!(as_failds.contains(&payment_hash_5));
5175 assert!(as_failds.contains(&payment_hash_6));
5177 let bs_events = nodes[1].node.get_and_clear_pending_events();
5178 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5179 let mut bs_failds = HashSet::new();
5180 let mut bs_updates = 0;
5181 for event in bs_events.iter() {
5182 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5183 assert!(bs_failds.insert(*payment_hash));
5184 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5185 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5187 assert!(!payment_failed_permanently);
5189 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5192 } else if let &Event::PaymentFailed { .. } = event {
5193 } else { panic!("Unexpected event"); }
5195 assert!(bs_failds.contains(&payment_hash_1));
5196 assert!(bs_failds.contains(&payment_hash_2));
5197 if announce_latest {
5198 assert!(bs_failds.contains(&payment_hash_4));
5200 assert!(bs_failds.contains(&payment_hash_5));
5202 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5203 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5204 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5205 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5206 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5207 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5211 fn test_fail_backwards_latest_remote_announce_a() {
5212 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5216 fn test_fail_backwards_latest_remote_announce_b() {
5217 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5221 fn test_fail_backwards_previous_remote_announce() {
5222 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5223 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5224 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5228 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5229 let chanmon_cfgs = create_chanmon_cfgs(2);
5230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5232 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5234 // Create some initial channels
5235 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5237 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5238 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5239 assert_eq!(local_txn[0].input.len(), 1);
5240 check_spends!(local_txn[0], chan_1.3);
5242 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5243 mine_transaction(&nodes[0], &local_txn[0]);
5244 check_closed_broadcast!(nodes[0], true);
5245 check_added_monitors!(nodes[0], 1);
5246 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5247 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5249 let htlc_timeout = {
5250 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5251 assert_eq!(node_txn.len(), 1);
5252 assert_eq!(node_txn[0].input.len(), 1);
5253 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5254 check_spends!(node_txn[0], local_txn[0]);
5258 mine_transaction(&nodes[0], &htlc_timeout);
5259 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5260 expect_payment_failed!(nodes[0], our_payment_hash, false);
5262 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5263 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5264 assert_eq!(spend_txn.len(), 3);
5265 check_spends!(spend_txn[0], local_txn[0]);
5266 assert_eq!(spend_txn[1].input.len(), 1);
5267 check_spends!(spend_txn[1], htlc_timeout);
5268 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5269 assert_eq!(spend_txn[2].input.len(), 2);
5270 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5271 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5272 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5276 fn test_key_derivation_params() {
5277 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5278 // manager rotation to test that `channel_keys_id` returned in
5279 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5280 // then derive a `delayed_payment_key`.
5282 let chanmon_cfgs = create_chanmon_cfgs(3);
5284 // We manually create the node configuration to backup the seed.
5285 let seed = [42; 32];
5286 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5287 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);
5288 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5289 let scorer = Mutex::new(test_utils::TestScorer::new());
5290 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5291 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)) };
5292 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5293 node_cfgs.remove(0);
5294 node_cfgs.insert(0, node);
5296 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5297 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5299 // Create some initial channels
5300 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5302 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5303 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5304 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5306 // Ensure all nodes are at the same height
5307 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5308 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5309 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5310 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5312 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5313 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5314 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5315 assert_eq!(local_txn_1[0].input.len(), 1);
5316 check_spends!(local_txn_1[0], chan_1.3);
5318 // We check funding pubkey are unique
5319 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]));
5320 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]));
5321 if from_0_funding_key_0 == from_1_funding_key_0
5322 || from_0_funding_key_0 == from_1_funding_key_1
5323 || from_0_funding_key_1 == from_1_funding_key_0
5324 || from_0_funding_key_1 == from_1_funding_key_1 {
5325 panic!("Funding pubkeys aren't unique");
5328 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5329 mine_transaction(&nodes[0], &local_txn_1[0]);
5330 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5331 check_closed_broadcast!(nodes[0], true);
5332 check_added_monitors!(nodes[0], 1);
5333 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5335 let htlc_timeout = {
5336 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5337 assert_eq!(node_txn.len(), 1);
5338 assert_eq!(node_txn[0].input.len(), 1);
5339 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5340 check_spends!(node_txn[0], local_txn_1[0]);
5344 mine_transaction(&nodes[0], &htlc_timeout);
5345 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5346 expect_payment_failed!(nodes[0], our_payment_hash, false);
5348 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5349 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5350 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5351 assert_eq!(spend_txn.len(), 3);
5352 check_spends!(spend_txn[0], local_txn_1[0]);
5353 assert_eq!(spend_txn[1].input.len(), 1);
5354 check_spends!(spend_txn[1], htlc_timeout);
5355 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5356 assert_eq!(spend_txn[2].input.len(), 2);
5357 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5358 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5359 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5363 fn test_static_output_closing_tx() {
5364 let chanmon_cfgs = create_chanmon_cfgs(2);
5365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5367 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5369 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5371 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5372 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5374 mine_transaction(&nodes[0], &closing_tx);
5375 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5376 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5378 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5379 assert_eq!(spend_txn.len(), 1);
5380 check_spends!(spend_txn[0], closing_tx);
5382 mine_transaction(&nodes[1], &closing_tx);
5383 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5384 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5386 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5387 assert_eq!(spend_txn.len(), 1);
5388 check_spends!(spend_txn[0], closing_tx);
5391 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5392 let chanmon_cfgs = create_chanmon_cfgs(2);
5393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5395 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5396 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5398 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5400 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5401 // present in B's local commitment transaction, but none of A's commitment transactions.
5402 nodes[1].node.claim_funds(payment_preimage);
5403 check_added_monitors!(nodes[1], 1);
5404 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5406 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5407 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5408 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5410 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5411 check_added_monitors!(nodes[0], 1);
5412 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5413 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5414 check_added_monitors!(nodes[1], 1);
5416 let starting_block = nodes[1].best_block_info();
5417 let mut block = Block {
5418 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5421 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5422 connect_block(&nodes[1], &block);
5423 block.header.prev_blockhash = block.block_hash();
5425 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5426 check_closed_broadcast!(nodes[1], true);
5427 check_added_monitors!(nodes[1], 1);
5428 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5431 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5432 let chanmon_cfgs = create_chanmon_cfgs(2);
5433 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5434 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5435 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5436 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5438 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5439 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5440 check_added_monitors!(nodes[0], 1);
5442 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5444 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5445 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5446 // to "time out" the HTLC.
5448 let starting_block = nodes[1].best_block_info();
5449 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5451 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5452 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5453 header.prev_blockhash = header.block_hash();
5455 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5456 check_closed_broadcast!(nodes[0], true);
5457 check_added_monitors!(nodes[0], 1);
5458 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5461 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5462 let chanmon_cfgs = create_chanmon_cfgs(3);
5463 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5464 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5465 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5466 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5468 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5469 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5470 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5471 // actually revoked.
5472 let htlc_value = if use_dust { 50000 } else { 3000000 };
5473 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5474 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5475 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5476 check_added_monitors!(nodes[1], 1);
5478 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5479 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5480 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5481 check_added_monitors!(nodes[0], 1);
5482 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5483 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5484 check_added_monitors!(nodes[1], 1);
5485 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5486 check_added_monitors!(nodes[1], 1);
5487 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5489 if check_revoke_no_close {
5490 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5491 check_added_monitors!(nodes[0], 1);
5494 let starting_block = nodes[1].best_block_info();
5495 let mut block = Block {
5496 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5499 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5500 connect_block(&nodes[0], &block);
5501 block.header.prev_blockhash = block.block_hash();
5503 if !check_revoke_no_close {
5504 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5505 check_closed_broadcast!(nodes[0], true);
5506 check_added_monitors!(nodes[0], 1);
5507 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5509 expect_payment_failed!(nodes[0], our_payment_hash, true);
5513 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5514 // There are only a few cases to test here:
5515 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5516 // broadcastable commitment transactions result in channel closure,
5517 // * its included in an unrevoked-but-previous remote commitment transaction,
5518 // * its included in the latest remote or local commitment transactions.
5519 // We test each of the three possible commitment transactions individually and use both dust and
5521 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5522 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5523 // tested for at least one of the cases in other tests.
5525 fn htlc_claim_single_commitment_only_a() {
5526 do_htlc_claim_local_commitment_only(true);
5527 do_htlc_claim_local_commitment_only(false);
5529 do_htlc_claim_current_remote_commitment_only(true);
5530 do_htlc_claim_current_remote_commitment_only(false);
5534 fn htlc_claim_single_commitment_only_b() {
5535 do_htlc_claim_previous_remote_commitment_only(true, false);
5536 do_htlc_claim_previous_remote_commitment_only(false, false);
5537 do_htlc_claim_previous_remote_commitment_only(true, true);
5538 do_htlc_claim_previous_remote_commitment_only(false, true);
5543 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5544 let chanmon_cfgs = create_chanmon_cfgs(2);
5545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5548 // Force duplicate randomness for every get-random call
5549 for node in nodes.iter() {
5550 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5553 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5554 let channel_value_satoshis=10000;
5555 let push_msat=10001;
5556 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5557 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5558 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5559 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5561 // Create a second channel with the same random values. This used to panic due to a colliding
5562 // channel_id, but now panics due to a colliding outbound SCID alias.
5563 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5567 fn bolt2_open_channel_sending_node_checks_part2() {
5568 let chanmon_cfgs = create_chanmon_cfgs(2);
5569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5573 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5574 let channel_value_satoshis=2^24;
5575 let push_msat=10001;
5576 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5578 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5579 let channel_value_satoshis=10000;
5580 // Test when push_msat is equal to 1000 * funding_satoshis.
5581 let push_msat=1000*channel_value_satoshis+1;
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 set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5585 let channel_value_satoshis=10000;
5586 let push_msat=10001;
5587 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
5588 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5589 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5591 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5592 // 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
5593 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5595 // 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.
5596 assert!(BREAKDOWN_TIMEOUT>0);
5597 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5599 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5600 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5601 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5603 // 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.
5604 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5605 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5606 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5607 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5608 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5612 fn bolt2_open_channel_sane_dust_limit() {
5613 let chanmon_cfgs = create_chanmon_cfgs(2);
5614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5616 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5618 let channel_value_satoshis=1000000;
5619 let push_msat=10001;
5620 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5621 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5622 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5623 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5625 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5626 let events = nodes[1].node.get_and_clear_pending_msg_events();
5627 let err_msg = match events[0] {
5628 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5631 _ => panic!("Unexpected event"),
5633 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5636 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5637 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5638 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5639 // is no longer affordable once it's freed.
5641 fn test_fail_holding_cell_htlc_upon_free() {
5642 let chanmon_cfgs = create_chanmon_cfgs(2);
5643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5645 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5646 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5648 // First nodes[0] generates an update_fee, setting the channel's
5649 // pending_update_fee.
5651 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5652 *feerate_lock += 20;
5654 nodes[0].node.timer_tick_occurred();
5655 check_added_monitors!(nodes[0], 1);
5657 let events = nodes[0].node.get_and_clear_pending_msg_events();
5658 assert_eq!(events.len(), 1);
5659 let (update_msg, commitment_signed) = match events[0] {
5660 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5661 (update_fee.as_ref(), commitment_signed)
5663 _ => panic!("Unexpected event"),
5666 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5668 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5669 let channel_reserve = chan_stat.channel_reserve_msat;
5670 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5671 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5673 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5674 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5675 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5677 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5678 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5679 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5680 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5682 // Flush the pending fee update.
5683 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5684 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5685 check_added_monitors!(nodes[1], 1);
5686 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5687 check_added_monitors!(nodes[0], 1);
5689 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5690 // HTLC, but now that the fee has been raised the payment will now fail, causing
5691 // us to surface its failure to the user.
5692 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5693 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5694 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);
5695 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 {}",
5696 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5697 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5699 // Check that the payment failed to be sent out.
5700 let events = nodes[0].node.get_and_clear_pending_events();
5701 assert_eq!(events.len(), 2);
5703 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5704 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5705 assert_eq!(our_payment_hash.clone(), *payment_hash);
5706 assert_eq!(*payment_failed_permanently, false);
5707 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5709 _ => panic!("Unexpected event"),
5712 &Event::PaymentFailed { ref payment_hash, .. } => {
5713 assert_eq!(our_payment_hash.clone(), *payment_hash);
5715 _ => panic!("Unexpected event"),
5719 // Test that if multiple HTLCs are released from the holding cell and one is
5720 // valid but the other is no longer valid upon release, the valid HTLC can be
5721 // successfully completed while the other one fails as expected.
5723 fn test_free_and_fail_holding_cell_htlcs() {
5724 let chanmon_cfgs = create_chanmon_cfgs(2);
5725 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5726 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5727 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5728 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5730 // First nodes[0] generates an update_fee, setting the channel's
5731 // pending_update_fee.
5733 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5734 *feerate_lock += 200;
5736 nodes[0].node.timer_tick_occurred();
5737 check_added_monitors!(nodes[0], 1);
5739 let events = nodes[0].node.get_and_clear_pending_msg_events();
5740 assert_eq!(events.len(), 1);
5741 let (update_msg, commitment_signed) = match events[0] {
5742 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5743 (update_fee.as_ref(), commitment_signed)
5745 _ => panic!("Unexpected event"),
5748 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5750 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5751 let channel_reserve = chan_stat.channel_reserve_msat;
5752 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5753 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5755 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5757 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5758 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5759 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5761 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5762 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5763 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5764 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5765 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5766 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5767 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5768 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5770 // Flush the pending fee update.
5771 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5772 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5773 check_added_monitors!(nodes[1], 1);
5774 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5775 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5776 check_added_monitors!(nodes[0], 2);
5778 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5779 // but now that the fee has been raised the second payment will now fail, causing us
5780 // to surface its failure to the user. The first payment should succeed.
5781 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5782 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5783 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);
5784 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 {}",
5785 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5786 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5788 // Check that the second payment failed to be sent out.
5789 let events = nodes[0].node.get_and_clear_pending_events();
5790 assert_eq!(events.len(), 2);
5792 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5793 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5794 assert_eq!(payment_hash_2.clone(), *payment_hash);
5795 assert_eq!(*payment_failed_permanently, false);
5796 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5798 _ => panic!("Unexpected event"),
5801 &Event::PaymentFailed { ref payment_hash, .. } => {
5802 assert_eq!(payment_hash_2.clone(), *payment_hash);
5804 _ => panic!("Unexpected event"),
5807 // Complete the first payment and the RAA from the fee update.
5808 let (payment_event, send_raa_event) = {
5809 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5810 assert_eq!(msgs.len(), 2);
5811 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5813 let raa = match send_raa_event {
5814 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5815 _ => panic!("Unexpected event"),
5817 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5818 check_added_monitors!(nodes[1], 1);
5819 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5820 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5821 let events = nodes[1].node.get_and_clear_pending_events();
5822 assert_eq!(events.len(), 1);
5824 Event::PendingHTLCsForwardable { .. } => {},
5825 _ => panic!("Unexpected event"),
5827 nodes[1].node.process_pending_htlc_forwards();
5828 let events = nodes[1].node.get_and_clear_pending_events();
5829 assert_eq!(events.len(), 1);
5831 Event::PaymentClaimable { .. } => {},
5832 _ => panic!("Unexpected event"),
5834 nodes[1].node.claim_funds(payment_preimage_1);
5835 check_added_monitors!(nodes[1], 1);
5836 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5838 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5839 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5840 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5841 expect_payment_sent!(nodes[0], payment_preimage_1);
5844 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5845 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5846 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5849 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5850 let chanmon_cfgs = create_chanmon_cfgs(3);
5851 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5852 // When this test was written, the default base fee floated based on the HTLC count.
5853 // It is now fixed, so we simply set the fee to the expected value here.
5854 let mut config = test_default_channel_config();
5855 config.channel_config.forwarding_fee_base_msat = 196;
5856 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5857 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5858 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5859 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5861 // First nodes[1] generates an update_fee, setting the channel's
5862 // pending_update_fee.
5864 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5865 *feerate_lock += 20;
5867 nodes[1].node.timer_tick_occurred();
5868 check_added_monitors!(nodes[1], 1);
5870 let events = nodes[1].node.get_and_clear_pending_msg_events();
5871 assert_eq!(events.len(), 1);
5872 let (update_msg, commitment_signed) = match events[0] {
5873 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5874 (update_fee.as_ref(), commitment_signed)
5876 _ => panic!("Unexpected event"),
5879 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5881 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5882 let channel_reserve = chan_stat.channel_reserve_msat;
5883 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5884 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5886 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5888 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5889 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5890 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5891 let payment_event = {
5892 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5893 check_added_monitors!(nodes[0], 1);
5895 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5896 assert_eq!(events.len(), 1);
5898 SendEvent::from_event(events.remove(0))
5900 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5901 check_added_monitors!(nodes[1], 0);
5902 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5903 expect_pending_htlcs_forwardable!(nodes[1]);
5905 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5906 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5908 // Flush the pending fee update.
5909 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5910 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5911 check_added_monitors!(nodes[2], 1);
5912 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5913 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5914 check_added_monitors!(nodes[1], 2);
5916 // A final RAA message is generated to finalize the fee update.
5917 let events = nodes[1].node.get_and_clear_pending_msg_events();
5918 assert_eq!(events.len(), 1);
5920 let raa_msg = match &events[0] {
5921 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5924 _ => panic!("Unexpected event"),
5927 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5928 check_added_monitors!(nodes[2], 1);
5929 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5931 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5932 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5933 assert_eq!(process_htlc_forwards_event.len(), 2);
5934 match &process_htlc_forwards_event[0] {
5935 &Event::PendingHTLCsForwardable { .. } => {},
5936 _ => panic!("Unexpected event"),
5939 // In response, we call ChannelManager's process_pending_htlc_forwards
5940 nodes[1].node.process_pending_htlc_forwards();
5941 check_added_monitors!(nodes[1], 1);
5943 // This causes the HTLC to be failed backwards.
5944 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5945 assert_eq!(fail_event.len(), 1);
5946 let (fail_msg, commitment_signed) = match &fail_event[0] {
5947 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5948 assert_eq!(updates.update_add_htlcs.len(), 0);
5949 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5950 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5951 assert_eq!(updates.update_fail_htlcs.len(), 1);
5952 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5954 _ => panic!("Unexpected event"),
5957 // Pass the failure messages back to nodes[0].
5958 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5961 // Complete the HTLC failure+removal process.
5962 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5963 check_added_monitors!(nodes[0], 1);
5964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5965 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5966 check_added_monitors!(nodes[1], 2);
5967 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5968 assert_eq!(final_raa_event.len(), 1);
5969 let raa = match &final_raa_event[0] {
5970 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5971 _ => panic!("Unexpected event"),
5973 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5974 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5975 check_added_monitors!(nodes[0], 1);
5978 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5979 // 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.
5980 //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.
5983 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5984 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5985 let chanmon_cfgs = create_chanmon_cfgs(2);
5986 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5987 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5988 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5989 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5991 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5992 route.paths[0][0].fee_msat = 100;
5994 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 },
5995 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5996 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5997 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6001 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6002 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6003 let chanmon_cfgs = create_chanmon_cfgs(2);
6004 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6005 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6006 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6007 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6009 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6010 route.paths[0][0].fee_msat = 0;
6011 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 },
6012 assert_eq!(err, "Cannot send 0-msat HTLC"));
6014 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6015 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6019 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6020 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6021 let chanmon_cfgs = create_chanmon_cfgs(2);
6022 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6023 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6024 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6025 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6027 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6028 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6029 check_added_monitors!(nodes[0], 1);
6030 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6031 updates.update_add_htlcs[0].amount_msat = 0;
6033 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6034 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6035 check_closed_broadcast!(nodes[1], true).unwrap();
6036 check_added_monitors!(nodes[1], 1);
6037 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6041 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6042 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6043 //It is enforced when constructing a route.
6044 let chanmon_cfgs = create_chanmon_cfgs(2);
6045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6047 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6048 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6050 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6051 .with_features(nodes[1].node.invoice_features());
6052 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6053 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6054 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 },
6055 assert_eq!(err, &"Channel CLTV overflowed?"));
6059 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6060 //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.
6061 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6062 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6063 let chanmon_cfgs = create_chanmon_cfgs(2);
6064 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6065 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6066 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6067 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6068 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6069 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6071 for i in 0..max_accepted_htlcs {
6072 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6073 let payment_event = {
6074 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6075 check_added_monitors!(nodes[0], 1);
6077 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6078 assert_eq!(events.len(), 1);
6079 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6080 assert_eq!(htlcs[0].htlc_id, i);
6084 SendEvent::from_event(events.remove(0))
6086 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6087 check_added_monitors!(nodes[1], 0);
6088 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6090 expect_pending_htlcs_forwardable!(nodes[1]);
6091 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6093 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6094 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 },
6095 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6097 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6098 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6102 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6103 //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.
6104 let chanmon_cfgs = create_chanmon_cfgs(2);
6105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6107 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6108 let channel_value = 100000;
6109 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6110 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6112 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6114 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6115 // Manually create a route over our max in flight (which our router normally automatically
6117 route.paths[0][0].fee_msat = max_in_flight + 1;
6118 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 },
6119 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)));
6121 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6122 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);
6124 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6127 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6129 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6130 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6131 let chanmon_cfgs = create_chanmon_cfgs(2);
6132 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6134 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6135 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6136 let htlc_minimum_msat: u64;
6138 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6139 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6140 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6141 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6144 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6145 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6146 check_added_monitors!(nodes[0], 1);
6147 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6148 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6149 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6150 assert!(nodes[1].node.list_channels().is_empty());
6151 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6152 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()));
6153 check_added_monitors!(nodes[1], 1);
6154 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6158 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6159 //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
6160 let chanmon_cfgs = create_chanmon_cfgs(2);
6161 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6162 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6163 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6164 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6166 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6167 let channel_reserve = chan_stat.channel_reserve_msat;
6168 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6169 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6170 // The 2* and +1 are for the fee spike reserve.
6171 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6173 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6174 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6175 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6176 check_added_monitors!(nodes[0], 1);
6177 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6179 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6180 // at this time channel-initiatee receivers are not required to enforce that senders
6181 // respect the fee_spike_reserve.
6182 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6183 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6185 assert!(nodes[1].node.list_channels().is_empty());
6186 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6187 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6188 check_added_monitors!(nodes[1], 1);
6189 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6193 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6194 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6195 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6196 let chanmon_cfgs = create_chanmon_cfgs(2);
6197 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6198 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6199 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6200 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6202 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6203 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6204 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6205 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6206 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6207 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6209 let mut msg = msgs::UpdateAddHTLC {
6213 payment_hash: our_payment_hash,
6214 cltv_expiry: htlc_cltv,
6215 onion_routing_packet: onion_packet.clone(),
6218 for i in 0..super::channel::OUR_MAX_HTLCS {
6219 msg.htlc_id = i as u64;
6220 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6222 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6223 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6225 assert!(nodes[1].node.list_channels().is_empty());
6226 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6227 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6228 check_added_monitors!(nodes[1], 1);
6229 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6233 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6234 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6235 let chanmon_cfgs = create_chanmon_cfgs(2);
6236 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6237 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6238 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6239 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6241 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6242 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6243 check_added_monitors!(nodes[0], 1);
6244 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6245 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;
6246 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6248 assert!(nodes[1].node.list_channels().is_empty());
6249 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6250 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6251 check_added_monitors!(nodes[1], 1);
6252 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6256 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6257 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6258 let chanmon_cfgs = create_chanmon_cfgs(2);
6259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6261 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6263 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6264 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6265 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6266 check_added_monitors!(nodes[0], 1);
6267 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6268 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6269 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6271 assert!(nodes[1].node.list_channels().is_empty());
6272 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6273 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6274 check_added_monitors!(nodes[1], 1);
6275 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6279 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6280 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6281 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6282 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6283 let chanmon_cfgs = create_chanmon_cfgs(2);
6284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6286 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288 create_announced_chan_between_nodes(&nodes, 0, 1);
6289 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6290 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6291 check_added_monitors!(nodes[0], 1);
6292 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6293 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6295 //Disconnect and Reconnect
6296 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6297 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6298 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();
6299 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6300 assert_eq!(reestablish_1.len(), 1);
6301 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();
6302 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6303 assert_eq!(reestablish_2.len(), 1);
6304 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6305 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6306 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6307 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6310 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6311 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6312 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6313 check_added_monitors!(nodes[1], 1);
6314 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6316 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6318 assert!(nodes[1].node.list_channels().is_empty());
6319 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6320 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6321 check_added_monitors!(nodes[1], 1);
6322 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6326 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6327 //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.
6329 let chanmon_cfgs = create_chanmon_cfgs(2);
6330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6333 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6334 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6335 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6337 check_added_monitors!(nodes[0], 1);
6338 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6339 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6341 let update_msg = msgs::UpdateFulfillHTLC{
6344 payment_preimage: our_payment_preimage,
6347 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6349 assert!(nodes[0].node.list_channels().is_empty());
6350 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6351 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()));
6352 check_added_monitors!(nodes[0], 1);
6353 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6357 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6358 //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.
6360 let chanmon_cfgs = create_chanmon_cfgs(2);
6361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6363 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6364 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6366 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6367 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6368 check_added_monitors!(nodes[0], 1);
6369 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6370 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6372 let update_msg = msgs::UpdateFailHTLC{
6375 reason: msgs::OnionErrorPacket { data: Vec::new()},
6378 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6380 assert!(nodes[0].node.list_channels().is_empty());
6381 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6382 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()));
6383 check_added_monitors!(nodes[0], 1);
6384 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6388 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6389 //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.
6391 let chanmon_cfgs = create_chanmon_cfgs(2);
6392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6397 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6398 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6399 check_added_monitors!(nodes[0], 1);
6400 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6401 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6402 let update_msg = msgs::UpdateFailMalformedHTLC{
6405 sha256_of_onion: [1; 32],
6406 failure_code: 0x8000,
6409 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6411 assert!(nodes[0].node.list_channels().is_empty());
6412 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6413 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()));
6414 check_added_monitors!(nodes[0], 1);
6415 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6419 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6420 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6422 let chanmon_cfgs = create_chanmon_cfgs(2);
6423 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426 create_announced_chan_between_nodes(&nodes, 0, 1);
6428 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6430 nodes[1].node.claim_funds(our_payment_preimage);
6431 check_added_monitors!(nodes[1], 1);
6432 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6434 let events = nodes[1].node.get_and_clear_pending_msg_events();
6435 assert_eq!(events.len(), 1);
6436 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6438 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, .. } } => {
6439 assert!(update_add_htlcs.is_empty());
6440 assert_eq!(update_fulfill_htlcs.len(), 1);
6441 assert!(update_fail_htlcs.is_empty());
6442 assert!(update_fail_malformed_htlcs.is_empty());
6443 assert!(update_fee.is_none());
6444 update_fulfill_htlcs[0].clone()
6446 _ => panic!("Unexpected event"),
6450 update_fulfill_msg.htlc_id = 1;
6452 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6454 assert!(nodes[0].node.list_channels().is_empty());
6455 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6456 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6457 check_added_monitors!(nodes[0], 1);
6458 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6462 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6463 //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.
6465 let chanmon_cfgs = create_chanmon_cfgs(2);
6466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6468 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6469 create_announced_chan_between_nodes(&nodes, 0, 1);
6471 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6473 nodes[1].node.claim_funds(our_payment_preimage);
6474 check_added_monitors!(nodes[1], 1);
6475 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6477 let events = nodes[1].node.get_and_clear_pending_msg_events();
6478 assert_eq!(events.len(), 1);
6479 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6481 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, .. } } => {
6482 assert!(update_add_htlcs.is_empty());
6483 assert_eq!(update_fulfill_htlcs.len(), 1);
6484 assert!(update_fail_htlcs.is_empty());
6485 assert!(update_fail_malformed_htlcs.is_empty());
6486 assert!(update_fee.is_none());
6487 update_fulfill_htlcs[0].clone()
6489 _ => panic!("Unexpected event"),
6493 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6495 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6497 assert!(nodes[0].node.list_channels().is_empty());
6498 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6499 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6500 check_added_monitors!(nodes[0], 1);
6501 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6505 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6506 //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.
6508 let chanmon_cfgs = create_chanmon_cfgs(2);
6509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6511 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6512 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6514 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6515 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6516 check_added_monitors!(nodes[0], 1);
6518 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6519 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6521 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6522 check_added_monitors!(nodes[1], 0);
6523 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6525 let events = nodes[1].node.get_and_clear_pending_msg_events();
6527 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6529 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, .. } } => {
6530 assert!(update_add_htlcs.is_empty());
6531 assert!(update_fulfill_htlcs.is_empty());
6532 assert!(update_fail_htlcs.is_empty());
6533 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6534 assert!(update_fee.is_none());
6535 update_fail_malformed_htlcs[0].clone()
6537 _ => panic!("Unexpected event"),
6540 update_msg.failure_code &= !0x8000;
6541 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6543 assert!(nodes[0].node.list_channels().is_empty());
6544 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6545 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6546 check_added_monitors!(nodes[0], 1);
6547 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6551 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6552 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6553 // * 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.
6555 let chanmon_cfgs = create_chanmon_cfgs(3);
6556 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6557 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6558 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6559 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6560 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6562 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6565 let mut payment_event = {
6566 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6567 check_added_monitors!(nodes[0], 1);
6568 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6569 assert_eq!(events.len(), 1);
6570 SendEvent::from_event(events.remove(0))
6572 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6573 check_added_monitors!(nodes[1], 0);
6574 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6575 expect_pending_htlcs_forwardable!(nodes[1]);
6576 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6577 assert_eq!(events_2.len(), 1);
6578 check_added_monitors!(nodes[1], 1);
6579 payment_event = SendEvent::from_event(events_2.remove(0));
6580 assert_eq!(payment_event.msgs.len(), 1);
6583 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6584 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6585 check_added_monitors!(nodes[2], 0);
6586 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6588 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6589 assert_eq!(events_3.len(), 1);
6590 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6592 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 } } => {
6593 assert!(update_add_htlcs.is_empty());
6594 assert!(update_fulfill_htlcs.is_empty());
6595 assert!(update_fail_htlcs.is_empty());
6596 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6597 assert!(update_fee.is_none());
6598 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6600 _ => panic!("Unexpected event"),
6604 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6606 check_added_monitors!(nodes[1], 0);
6607 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6608 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 }]);
6609 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6610 assert_eq!(events_4.len(), 1);
6612 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6614 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, .. } } => {
6615 assert!(update_add_htlcs.is_empty());
6616 assert!(update_fulfill_htlcs.is_empty());
6617 assert_eq!(update_fail_htlcs.len(), 1);
6618 assert!(update_fail_malformed_htlcs.is_empty());
6619 assert!(update_fee.is_none());
6621 _ => panic!("Unexpected event"),
6624 check_added_monitors!(nodes[1], 1);
6628 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6629 let chanmon_cfgs = create_chanmon_cfgs(3);
6630 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6631 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6632 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6633 create_announced_chan_between_nodes(&nodes, 0, 1);
6634 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6636 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6639 let mut payment_event = {
6640 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6641 check_added_monitors!(nodes[0], 1);
6642 SendEvent::from_node(&nodes[0])
6645 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6646 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6647 expect_pending_htlcs_forwardable!(nodes[1]);
6648 check_added_monitors!(nodes[1], 1);
6649 payment_event = SendEvent::from_node(&nodes[1]);
6650 assert_eq!(payment_event.msgs.len(), 1);
6653 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6654 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6655 check_added_monitors!(nodes[2], 0);
6656 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6658 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6659 assert_eq!(events_3.len(), 1);
6661 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6662 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6663 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6664 update_msg.failure_code |= 0x2000;
6666 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6667 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6669 _ => panic!("Unexpected event"),
6672 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6673 vec![HTLCDestination::NextHopChannel {
6674 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6675 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6676 assert_eq!(events_4.len(), 1);
6677 check_added_monitors!(nodes[1], 1);
6680 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6681 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6682 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6684 _ => panic!("Unexpected event"),
6687 let events_5 = nodes[0].node.get_and_clear_pending_events();
6688 assert_eq!(events_5.len(), 2);
6690 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6691 // the node originating the error to its next hop.
6693 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6695 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6696 assert!(is_permanent);
6697 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6699 _ => panic!("Unexpected event"),
6702 Event::PaymentFailed { payment_hash, .. } => {
6703 assert_eq!(payment_hash, our_payment_hash);
6705 _ => panic!("Unexpected event"),
6708 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6711 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6712 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6713 // 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
6714 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6716 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6717 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6721 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6723 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6724 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6726 // We route 2 dust-HTLCs between A and B
6727 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6728 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6729 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6731 // Cache one local commitment tx as previous
6732 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6734 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6735 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6736 check_added_monitors!(nodes[1], 0);
6737 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6738 check_added_monitors!(nodes[1], 1);
6740 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6741 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6742 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6743 check_added_monitors!(nodes[0], 1);
6745 // Cache one local commitment tx as lastest
6746 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6748 let events = nodes[0].node.get_and_clear_pending_msg_events();
6750 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6751 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6753 _ => panic!("Unexpected event"),
6756 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6757 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6759 _ => panic!("Unexpected event"),
6762 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6763 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6764 if announce_latest {
6765 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6767 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6770 check_closed_broadcast!(nodes[0], true);
6771 check_added_monitors!(nodes[0], 1);
6772 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6774 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6775 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6776 let events = nodes[0].node.get_and_clear_pending_events();
6777 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6778 assert_eq!(events.len(), 4);
6779 let mut first_failed = false;
6780 for event in events {
6782 Event::PaymentPathFailed { payment_hash, .. } => {
6783 if payment_hash == payment_hash_1 {
6784 assert!(!first_failed);
6785 first_failed = true;
6787 assert_eq!(payment_hash, payment_hash_2);
6790 Event::PaymentFailed { .. } => {}
6791 _ => panic!("Unexpected event"),
6797 fn test_failure_delay_dust_htlc_local_commitment() {
6798 do_test_failure_delay_dust_htlc_local_commitment(true);
6799 do_test_failure_delay_dust_htlc_local_commitment(false);
6802 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6803 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6804 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6805 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6806 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6807 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6808 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6810 let chanmon_cfgs = create_chanmon_cfgs(3);
6811 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6812 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6813 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6814 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6816 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6817 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6819 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6820 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6822 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6823 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6825 // We revoked bs_commitment_tx
6827 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6828 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6831 let mut timeout_tx = Vec::new();
6833 // We fail dust-HTLC 1 by broadcast of local commitment tx
6834 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6835 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6836 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6837 expect_payment_failed!(nodes[0], dust_hash, false);
6839 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6840 check_closed_broadcast!(nodes[0], true);
6841 check_added_monitors!(nodes[0], 1);
6842 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6843 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6844 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6845 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6846 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6847 mine_transaction(&nodes[0], &timeout_tx[0]);
6848 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6849 expect_payment_failed!(nodes[0], non_dust_hash, false);
6851 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6852 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6853 check_closed_broadcast!(nodes[0], true);
6854 check_added_monitors!(nodes[0], 1);
6855 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6856 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6858 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6859 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6860 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6861 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6862 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6863 // dust HTLC should have been failed.
6864 expect_payment_failed!(nodes[0], dust_hash, false);
6867 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6869 assert_eq!(timeout_tx[0].lock_time.0, 12);
6871 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6872 mine_transaction(&nodes[0], &timeout_tx[0]);
6873 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6874 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6875 expect_payment_failed!(nodes[0], non_dust_hash, false);
6880 fn test_sweep_outbound_htlc_failure_update() {
6881 do_test_sweep_outbound_htlc_failure_update(false, true);
6882 do_test_sweep_outbound_htlc_failure_update(false, false);
6883 do_test_sweep_outbound_htlc_failure_update(true, false);
6887 fn test_user_configurable_csv_delay() {
6888 // We test our channel constructors yield errors when we pass them absurd csv delay
6890 let mut low_our_to_self_config = UserConfig::default();
6891 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6892 let mut high_their_to_self_config = UserConfig::default();
6893 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6894 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6895 let chanmon_cfgs = create_chanmon_cfgs(2);
6896 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6897 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6898 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6900 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6901 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6902 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6903 &low_our_to_self_config, 0, 42)
6906 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())); },
6907 _ => panic!("Unexpected event"),
6909 } else { assert!(false) }
6911 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6912 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6913 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6914 open_channel.to_self_delay = 200;
6915 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6916 &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,
6917 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6920 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())); },
6921 _ => panic!("Unexpected event"),
6923 } else { assert!(false); }
6925 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6926 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6927 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()));
6928 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6929 accept_channel.to_self_delay = 200;
6930 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6932 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6934 &ErrorAction::SendErrorMessage { ref msg } => {
6935 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()));
6936 reason_msg = msg.data.clone();
6940 } else { panic!(); }
6941 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6943 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6944 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6945 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6946 open_channel.to_self_delay = 200;
6947 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6948 &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,
6949 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6952 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())); },
6953 _ => panic!("Unexpected event"),
6955 } else { assert!(false); }
6959 fn test_check_htlc_underpaying() {
6960 // Send payment through A -> B but A is maliciously
6961 // sending a probe payment (i.e less than expected value0
6962 // to B, B should refuse payment.
6964 let chanmon_cfgs = create_chanmon_cfgs(2);
6965 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6966 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6967 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6969 // Create some initial channels
6970 create_announced_chan_between_nodes(&nodes, 0, 1);
6972 let scorer = test_utils::TestScorer::new();
6973 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6974 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6975 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();
6976 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6977 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6978 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6979 check_added_monitors!(nodes[0], 1);
6981 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6982 assert_eq!(events.len(), 1);
6983 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6984 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6985 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6987 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6988 // and then will wait a second random delay before failing the HTLC back:
6989 expect_pending_htlcs_forwardable!(nodes[1]);
6990 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6992 // Node 3 is expecting payment of 100_000 but received 10_000,
6993 // it should fail htlc like we didn't know the preimage.
6994 nodes[1].node.process_pending_htlc_forwards();
6996 let events = nodes[1].node.get_and_clear_pending_msg_events();
6997 assert_eq!(events.len(), 1);
6998 let (update_fail_htlc, commitment_signed) = match events[0] {
6999 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 } } => {
7000 assert!(update_add_htlcs.is_empty());
7001 assert!(update_fulfill_htlcs.is_empty());
7002 assert_eq!(update_fail_htlcs.len(), 1);
7003 assert!(update_fail_malformed_htlcs.is_empty());
7004 assert!(update_fee.is_none());
7005 (update_fail_htlcs[0].clone(), commitment_signed)
7007 _ => panic!("Unexpected event"),
7009 check_added_monitors!(nodes[1], 1);
7011 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7012 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7014 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7015 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7016 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7017 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7021 fn test_announce_disable_channels() {
7022 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7023 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7025 let chanmon_cfgs = create_chanmon_cfgs(2);
7026 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7028 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7030 create_announced_chan_between_nodes(&nodes, 0, 1);
7031 create_announced_chan_between_nodes(&nodes, 1, 0);
7032 create_announced_chan_between_nodes(&nodes, 0, 1);
7035 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7036 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7038 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7039 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7040 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7041 assert_eq!(msg_events.len(), 3);
7042 let mut chans_disabled = HashMap::new();
7043 for e in msg_events {
7045 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7046 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7047 // Check that each channel gets updated exactly once
7048 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7049 panic!("Generated ChannelUpdate for wrong chan!");
7052 _ => panic!("Unexpected event"),
7056 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();
7057 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7058 assert_eq!(reestablish_1.len(), 3);
7059 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();
7060 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7061 assert_eq!(reestablish_2.len(), 3);
7063 // Reestablish chan_1
7064 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7065 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7066 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7067 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7068 // Reestablish chan_2
7069 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7070 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7071 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7072 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7073 // Reestablish chan_3
7074 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7075 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7076 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7077 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7079 nodes[0].node.timer_tick_occurred();
7080 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7081 nodes[0].node.timer_tick_occurred();
7082 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7083 assert_eq!(msg_events.len(), 3);
7084 for e in msg_events {
7086 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7087 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7088 match chans_disabled.remove(&msg.contents.short_channel_id) {
7089 // Each update should have a higher timestamp than the previous one, replacing
7091 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7092 None => panic!("Generated ChannelUpdate for wrong chan!"),
7095 _ => panic!("Unexpected event"),
7098 // Check that each channel gets updated exactly once
7099 assert!(chans_disabled.is_empty());
7103 fn test_bump_penalty_txn_on_revoked_commitment() {
7104 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7105 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7107 let chanmon_cfgs = create_chanmon_cfgs(2);
7108 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7109 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7110 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7112 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7114 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7115 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7116 .with_features(nodes[0].node.invoice_features());
7117 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7118 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7120 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7121 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7122 assert_eq!(revoked_txn[0].output.len(), 4);
7123 assert_eq!(revoked_txn[0].input.len(), 1);
7124 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7125 let revoked_txid = revoked_txn[0].txid();
7127 let mut penalty_sum = 0;
7128 for outp in revoked_txn[0].output.iter() {
7129 if outp.script_pubkey.is_v0_p2wsh() {
7130 penalty_sum += outp.value;
7134 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7135 let header_114 = connect_blocks(&nodes[1], 14);
7137 // Actually revoke tx by claiming a HTLC
7138 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7139 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7140 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7141 check_added_monitors!(nodes[1], 1);
7143 // One or more justice tx should have been broadcast, check it
7147 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7148 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7149 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7150 assert_eq!(node_txn[0].output.len(), 1);
7151 check_spends!(node_txn[0], revoked_txn[0]);
7152 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7153 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7154 penalty_1 = node_txn[0].txid();
7158 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7159 connect_blocks(&nodes[1], 15);
7160 let mut penalty_2 = penalty_1;
7161 let mut feerate_2 = 0;
7163 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7164 assert_eq!(node_txn.len(), 1);
7165 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7166 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7167 assert_eq!(node_txn[0].output.len(), 1);
7168 check_spends!(node_txn[0], revoked_txn[0]);
7169 penalty_2 = node_txn[0].txid();
7170 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7171 assert_ne!(penalty_2, penalty_1);
7172 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7173 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7174 // Verify 25% bump heuristic
7175 assert!(feerate_2 * 100 >= feerate_1 * 125);
7179 assert_ne!(feerate_2, 0);
7181 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7182 connect_blocks(&nodes[1], 1);
7184 let mut feerate_3 = 0;
7186 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7187 assert_eq!(node_txn.len(), 1);
7188 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7189 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7190 assert_eq!(node_txn[0].output.len(), 1);
7191 check_spends!(node_txn[0], revoked_txn[0]);
7192 penalty_3 = node_txn[0].txid();
7193 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7194 assert_ne!(penalty_3, penalty_2);
7195 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7196 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7197 // Verify 25% bump heuristic
7198 assert!(feerate_3 * 100 >= feerate_2 * 125);
7202 assert_ne!(feerate_3, 0);
7204 nodes[1].node.get_and_clear_pending_events();
7205 nodes[1].node.get_and_clear_pending_msg_events();
7209 fn test_bump_penalty_txn_on_revoked_htlcs() {
7210 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7211 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7213 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7214 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7215 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7216 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7217 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7219 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7220 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7221 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7222 let scorer = test_utils::TestScorer::new();
7223 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7224 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7225 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7226 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7227 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7228 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7229 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7230 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7232 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7233 assert_eq!(revoked_local_txn[0].input.len(), 1);
7234 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7236 // Revoke local commitment tx
7237 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7239 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7240 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7241 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7242 check_closed_broadcast!(nodes[1], true);
7243 check_added_monitors!(nodes[1], 1);
7244 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7245 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7247 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7248 assert_eq!(revoked_htlc_txn.len(), 2);
7250 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7251 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7252 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7254 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7255 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7256 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7257 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7259 // Broadcast set of revoked txn on A
7260 let hash_128 = connect_blocks(&nodes[0], 40);
7261 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7262 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7263 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7264 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7265 let events = nodes[0].node.get_and_clear_pending_events();
7266 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7267 match events.last().unwrap() {
7268 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7269 _ => panic!("Unexpected event"),
7275 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7276 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7277 // Verify claim tx are spending revoked HTLC txn
7279 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7280 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7281 // which are included in the same block (they are broadcasted because we scan the
7282 // transactions linearly and generate claims as we go, they likely should be removed in the
7284 assert_eq!(node_txn[0].input.len(), 1);
7285 check_spends!(node_txn[0], revoked_local_txn[0]);
7286 assert_eq!(node_txn[1].input.len(), 1);
7287 check_spends!(node_txn[1], revoked_local_txn[0]);
7288 assert_eq!(node_txn[2].input.len(), 1);
7289 check_spends!(node_txn[2], revoked_local_txn[0]);
7291 // Each of the three justice transactions claim a separate (single) output of the three
7292 // available, which we check here:
7293 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7294 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7295 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7297 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7298 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7300 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7301 // output, checked above).
7302 assert_eq!(node_txn[3].input.len(), 2);
7303 assert_eq!(node_txn[3].output.len(), 1);
7304 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7306 first = node_txn[3].txid();
7307 // Store both feerates for later comparison
7308 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7309 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7310 penalty_txn = vec![node_txn[2].clone()];
7314 // Connect one more block to see if bumped penalty are issued for HTLC txn
7315 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7316 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7317 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7318 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7320 // Few more blocks to confirm penalty txn
7321 connect_blocks(&nodes[0], 4);
7322 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7323 let header_144 = connect_blocks(&nodes[0], 9);
7325 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7326 assert_eq!(node_txn.len(), 1);
7328 assert_eq!(node_txn[0].input.len(), 2);
7329 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7330 // Verify bumped tx is different and 25% bump heuristic
7331 assert_ne!(first, node_txn[0].txid());
7332 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7333 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7334 assert!(feerate_2 * 100 > feerate_1 * 125);
7335 let txn = vec![node_txn[0].clone()];
7339 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7340 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7341 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7342 connect_blocks(&nodes[0], 20);
7344 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7345 // We verify than no new transaction has been broadcast because previously
7346 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7347 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7348 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7349 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7350 // up bumped justice generation.
7351 assert_eq!(node_txn.len(), 0);
7354 check_closed_broadcast!(nodes[0], true);
7355 check_added_monitors!(nodes[0], 1);
7359 fn test_bump_penalty_txn_on_remote_commitment() {
7360 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7361 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7364 // Provide preimage for one
7365 // Check aggregation
7367 let chanmon_cfgs = create_chanmon_cfgs(2);
7368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7370 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7372 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7373 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7374 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7376 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7377 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7378 assert_eq!(remote_txn[0].output.len(), 4);
7379 assert_eq!(remote_txn[0].input.len(), 1);
7380 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7382 // Claim a HTLC without revocation (provide B monitor with preimage)
7383 nodes[1].node.claim_funds(payment_preimage);
7384 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7385 mine_transaction(&nodes[1], &remote_txn[0]);
7386 check_added_monitors!(nodes[1], 2);
7387 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7389 // One or more claim tx should have been broadcast, check it
7393 let feerate_timeout;
7394 let feerate_preimage;
7396 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7397 // 3 transactions including:
7398 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7399 assert_eq!(node_txn.len(), 3);
7400 assert_eq!(node_txn[0].input.len(), 1);
7401 assert_eq!(node_txn[1].input.len(), 1);
7402 assert_eq!(node_txn[2].input.len(), 1);
7403 check_spends!(node_txn[0], remote_txn[0]);
7404 check_spends!(node_txn[1], remote_txn[0]);
7405 check_spends!(node_txn[2], remote_txn[0]);
7407 preimage = node_txn[0].txid();
7408 let index = node_txn[0].input[0].previous_output.vout;
7409 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7410 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7412 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7413 (node_txn[2].clone(), node_txn[1].clone())
7415 (node_txn[1].clone(), node_txn[2].clone())
7418 preimage_bump = preimage_bump_tx;
7419 check_spends!(preimage_bump, remote_txn[0]);
7420 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7422 timeout = timeout_tx.txid();
7423 let index = timeout_tx.input[0].previous_output.vout;
7424 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7425 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7429 assert_ne!(feerate_timeout, 0);
7430 assert_ne!(feerate_preimage, 0);
7432 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7433 connect_blocks(&nodes[1], 15);
7435 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7436 assert_eq!(node_txn.len(), 1);
7437 assert_eq!(node_txn[0].input.len(), 1);
7438 assert_eq!(preimage_bump.input.len(), 1);
7439 check_spends!(node_txn[0], remote_txn[0]);
7440 check_spends!(preimage_bump, remote_txn[0]);
7442 let index = preimage_bump.input[0].previous_output.vout;
7443 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7444 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7445 assert!(new_feerate * 100 > feerate_timeout * 125);
7446 assert_ne!(timeout, preimage_bump.txid());
7448 let index = node_txn[0].input[0].previous_output.vout;
7449 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7450 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7451 assert!(new_feerate * 100 > feerate_preimage * 125);
7452 assert_ne!(preimage, node_txn[0].txid());
7457 nodes[1].node.get_and_clear_pending_events();
7458 nodes[1].node.get_and_clear_pending_msg_events();
7462 fn test_counterparty_raa_skip_no_crash() {
7463 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7464 // commitment transaction, we would have happily carried on and provided them the next
7465 // commitment transaction based on one RAA forward. This would probably eventually have led to
7466 // channel closure, but it would not have resulted in funds loss. Still, our
7467 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7468 // check simply that the channel is closed in response to such an RAA, but don't check whether
7469 // we decide to punish our counterparty for revoking their funds (as we don't currently
7471 let chanmon_cfgs = create_chanmon_cfgs(2);
7472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7475 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7477 let per_commitment_secret;
7478 let next_per_commitment_point;
7480 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7481 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7482 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7484 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7486 // Make signer believe we got a counterparty signature, so that it allows the revocation
7487 keys.get_enforcement_state().last_holder_commitment -= 1;
7488 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7490 // Must revoke without gaps
7491 keys.get_enforcement_state().last_holder_commitment -= 1;
7492 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7494 keys.get_enforcement_state().last_holder_commitment -= 1;
7495 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7496 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7499 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7500 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7501 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7502 check_added_monitors!(nodes[1], 1);
7503 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7507 fn test_bump_txn_sanitize_tracking_maps() {
7508 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7509 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7511 let chanmon_cfgs = create_chanmon_cfgs(2);
7512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7516 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7517 // Lock HTLC in both directions
7518 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7519 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7521 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7522 assert_eq!(revoked_local_txn[0].input.len(), 1);
7523 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7525 // Revoke local commitment tx
7526 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7528 // Broadcast set of revoked txn on A
7529 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7530 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7531 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7533 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7534 check_closed_broadcast!(nodes[0], true);
7535 check_added_monitors!(nodes[0], 1);
7536 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7538 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7539 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7540 check_spends!(node_txn[0], revoked_local_txn[0]);
7541 check_spends!(node_txn[1], revoked_local_txn[0]);
7542 check_spends!(node_txn[2], revoked_local_txn[0]);
7543 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7547 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7548 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7549 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7551 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7552 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7553 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7558 fn test_pending_claimed_htlc_no_balance_underflow() {
7559 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7560 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7561 let chanmon_cfgs = create_chanmon_cfgs(2);
7562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7565 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7567 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7568 nodes[1].node.claim_funds(payment_preimage);
7569 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7570 check_added_monitors!(nodes[1], 1);
7571 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7573 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7574 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7575 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7576 check_added_monitors!(nodes[0], 1);
7577 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7579 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7580 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7581 // can get our balance.
7583 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7584 // the public key of the only hop. This works around ChannelDetails not showing the
7585 // almost-claimed HTLC as available balance.
7586 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7587 route.payment_params = None; // This is all wrong, but unnecessary
7588 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7589 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7590 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7592 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7596 fn test_channel_conf_timeout() {
7597 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7598 // confirm within 2016 blocks, as recommended by BOLT 2.
7599 let chanmon_cfgs = create_chanmon_cfgs(2);
7600 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7602 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7604 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7606 // The outbound node should wait forever for confirmation:
7607 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7608 // copied here instead of directly referencing the constant.
7609 connect_blocks(&nodes[0], 2016);
7610 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7612 // The inbound node should fail the channel after exactly 2016 blocks
7613 connect_blocks(&nodes[1], 2015);
7614 check_added_monitors!(nodes[1], 0);
7615 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7617 connect_blocks(&nodes[1], 1);
7618 check_added_monitors!(nodes[1], 1);
7619 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7620 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7621 assert_eq!(close_ev.len(), 1);
7623 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7624 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7625 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7627 _ => panic!("Unexpected event"),
7632 fn test_override_channel_config() {
7633 let chanmon_cfgs = create_chanmon_cfgs(2);
7634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638 // Node0 initiates a channel to node1 using the override config.
7639 let mut override_config = UserConfig::default();
7640 override_config.channel_handshake_config.our_to_self_delay = 200;
7642 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7644 // Assert the channel created by node0 is using the override config.
7645 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7646 assert_eq!(res.channel_flags, 0);
7647 assert_eq!(res.to_self_delay, 200);
7651 fn test_override_0msat_htlc_minimum() {
7652 let mut zero_config = UserConfig::default();
7653 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7654 let chanmon_cfgs = create_chanmon_cfgs(2);
7655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7657 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7659 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7660 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7661 assert_eq!(res.htlc_minimum_msat, 1);
7663 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7664 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7665 assert_eq!(res.htlc_minimum_msat, 1);
7669 fn test_channel_update_has_correct_htlc_maximum_msat() {
7670 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7671 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7672 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7673 // 90% of the `channel_value`.
7674 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7676 let mut config_30_percent = UserConfig::default();
7677 config_30_percent.channel_handshake_config.announced_channel = true;
7678 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7679 let mut config_50_percent = UserConfig::default();
7680 config_50_percent.channel_handshake_config.announced_channel = true;
7681 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7682 let mut config_95_percent = UserConfig::default();
7683 config_95_percent.channel_handshake_config.announced_channel = true;
7684 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7685 let mut config_100_percent = UserConfig::default();
7686 config_100_percent.channel_handshake_config.announced_channel = true;
7687 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7689 let chanmon_cfgs = create_chanmon_cfgs(4);
7690 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7691 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)]);
7692 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7694 let channel_value_satoshis = 100000;
7695 let channel_value_msat = channel_value_satoshis * 1000;
7696 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7697 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7698 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7700 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7701 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7703 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7704 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7705 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7706 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7707 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7708 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7710 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7711 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7713 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7714 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7715 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7717 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7721 fn test_manually_accept_inbound_channel_request() {
7722 let mut manually_accept_conf = UserConfig::default();
7723 manually_accept_conf.manually_accept_inbound_channels = true;
7724 let chanmon_cfgs = create_chanmon_cfgs(2);
7725 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7726 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7727 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7729 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7730 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7732 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7734 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7735 // accepting the inbound channel request.
7736 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7738 let events = nodes[1].node.get_and_clear_pending_events();
7740 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7741 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7743 _ => panic!("Unexpected event"),
7746 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7747 assert_eq!(accept_msg_ev.len(), 1);
7749 match accept_msg_ev[0] {
7750 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7751 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7753 _ => panic!("Unexpected event"),
7756 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7758 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7759 assert_eq!(close_msg_ev.len(), 1);
7761 let events = nodes[1].node.get_and_clear_pending_events();
7763 Event::ChannelClosed { user_channel_id, .. } => {
7764 assert_eq!(user_channel_id, 23);
7766 _ => panic!("Unexpected event"),
7771 fn test_manually_reject_inbound_channel_request() {
7772 let mut manually_accept_conf = UserConfig::default();
7773 manually_accept_conf.manually_accept_inbound_channels = true;
7774 let chanmon_cfgs = create_chanmon_cfgs(2);
7775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7777 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7779 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7780 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7782 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7784 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7785 // rejecting the inbound channel request.
7786 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7788 let events = nodes[1].node.get_and_clear_pending_events();
7790 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7791 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7793 _ => panic!("Unexpected event"),
7796 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7797 assert_eq!(close_msg_ev.len(), 1);
7799 match close_msg_ev[0] {
7800 MessageSendEvent::HandleError { ref node_id, .. } => {
7801 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7803 _ => panic!("Unexpected event"),
7805 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7809 fn test_reject_funding_before_inbound_channel_accepted() {
7810 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7811 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7812 // the node operator before the counterparty sends a `FundingCreated` message. If a
7813 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7814 // and the channel should be closed.
7815 let mut manually_accept_conf = UserConfig::default();
7816 manually_accept_conf.manually_accept_inbound_channels = true;
7817 let chanmon_cfgs = create_chanmon_cfgs(2);
7818 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7819 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7820 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7822 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7823 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7824 let temp_channel_id = res.temporary_channel_id;
7826 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7828 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7829 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7831 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7832 nodes[1].node.get_and_clear_pending_events();
7834 // Get the `AcceptChannel` message of `nodes[1]` without calling
7835 // `ChannelManager::accept_inbound_channel`, which generates a
7836 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7837 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7838 // succeed when `nodes[0]` is passed to it.
7839 let accept_chan_msg = {
7840 let mut node_1_per_peer_lock;
7841 let mut node_1_peer_state_lock;
7842 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7843 channel.get_accept_channel_message()
7845 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7847 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7849 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7850 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7852 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7853 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7855 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7856 assert_eq!(close_msg_ev.len(), 1);
7858 let expected_err = "FundingCreated message received before the channel was accepted";
7859 match close_msg_ev[0] {
7860 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7861 assert_eq!(msg.channel_id, temp_channel_id);
7862 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7863 assert_eq!(msg.data, expected_err);
7865 _ => panic!("Unexpected event"),
7868 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7872 fn test_can_not_accept_inbound_channel_twice() {
7873 let mut manually_accept_conf = UserConfig::default();
7874 manually_accept_conf.manually_accept_inbound_channels = true;
7875 let chanmon_cfgs = create_chanmon_cfgs(2);
7876 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7877 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7878 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7880 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7881 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7883 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7885 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7886 // accepting the inbound channel request.
7887 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7889 let events = nodes[1].node.get_and_clear_pending_events();
7891 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7892 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7893 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7895 Err(APIError::APIMisuseError { err }) => {
7896 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7898 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7899 Err(_) => panic!("Unexpected Error"),
7902 _ => panic!("Unexpected event"),
7905 // Ensure that the channel wasn't closed after attempting to accept it twice.
7906 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7907 assert_eq!(accept_msg_ev.len(), 1);
7909 match accept_msg_ev[0] {
7910 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7911 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7913 _ => panic!("Unexpected event"),
7918 fn test_can_not_accept_unknown_inbound_channel() {
7919 let chanmon_cfg = create_chanmon_cfgs(2);
7920 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7921 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7922 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7924 let unknown_channel_id = [0; 32];
7925 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7927 Err(APIError::ChannelUnavailable { err }) => {
7928 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()));
7930 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7931 Err(_) => panic!("Unexpected Error"),
7936 fn test_onion_value_mpp_set_calculation() {
7937 // Test that we use the onion value `amt_to_forward` when
7938 // calculating whether we've reached the `total_msat` of an MPP
7939 // by having a routing node forward more than `amt_to_forward`
7940 // and checking that the receiving node doesn't generate
7941 // a PaymentClaimable event too early
7943 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7944 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7945 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7946 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7948 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7949 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7950 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7951 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7953 let total_msat = 100_000;
7954 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7955 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7956 let sample_path = route.paths.pop().unwrap();
7958 let mut path_1 = sample_path.clone();
7959 path_1[0].pubkey = nodes[1].node.get_our_node_id();
7960 path_1[0].short_channel_id = chan_1_id;
7961 path_1[1].pubkey = nodes[3].node.get_our_node_id();
7962 path_1[1].short_channel_id = chan_3_id;
7963 path_1[1].fee_msat = 100_000;
7964 route.paths.push(path_1);
7966 let mut path_2 = sample_path.clone();
7967 path_2[0].pubkey = nodes[2].node.get_our_node_id();
7968 path_2[0].short_channel_id = chan_2_id;
7969 path_2[1].pubkey = nodes[3].node.get_our_node_id();
7970 path_2[1].short_channel_id = chan_4_id;
7971 path_2[1].fee_msat = 1_000;
7972 route.paths.push(path_2);
7975 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7976 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
7977 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();
7978 check_added_monitors!(nodes[0], expected_paths.len());
7980 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7981 assert_eq!(events.len(), expected_paths.len());
7984 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
7985 let mut payment_event = SendEvent::from_event(ev);
7986 let mut prev_node = &nodes[0];
7988 for (idx, &node) in expected_paths[0].iter().enumerate() {
7989 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
7991 if idx == 0 { // routing node
7992 let session_priv = [3; 32];
7993 let height = nodes[0].best_block_info().1;
7994 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
7995 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
7996 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000, &Some(our_payment_secret), height + 1, &None).unwrap();
7997 // Edit amt_to_forward to simulate the sender having set
7998 // the final amount and the routing node taking less fee
7999 onion_payloads[1].amt_to_forward = 99_000;
8000 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8001 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8004 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8005 check_added_monitors!(node, 0);
8006 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8007 expect_pending_htlcs_forwardable!(node);
8010 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8011 assert_eq!(events_2.len(), 1);
8012 check_added_monitors!(node, 1);
8013 payment_event = SendEvent::from_event(events_2.remove(0));
8014 assert_eq!(payment_event.msgs.len(), 1);
8016 let events_2 = node.node.get_and_clear_pending_events();
8017 assert!(events_2.is_empty());
8024 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8025 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8027 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8030 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8032 let routing_node_count = msat_amounts.len();
8033 let node_count = routing_node_count + 2;
8035 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8036 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8037 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8038 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8043 // Create channels for each amount
8044 let mut expected_paths = Vec::with_capacity(routing_node_count);
8045 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8046 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8047 for i in 0..routing_node_count {
8048 let routing_node = 2 + i;
8049 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8050 src_chan_ids.push(src_chan_id);
8051 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8052 dst_chan_ids.push(dst_chan_id);
8053 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8054 expected_paths.push(path);
8056 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8058 // Create a route for each amount
8059 let example_amount = 100000;
8060 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);
8061 let sample_path = route.paths.pop().unwrap();
8062 for i in 0..routing_node_count {
8063 let routing_node = 2 + i;
8064 let mut path = sample_path.clone();
8065 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8066 path[0].short_channel_id = src_chan_ids[i];
8067 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8068 path[1].short_channel_id = dst_chan_ids[i];
8069 path[1].fee_msat = msat_amounts[i];
8070 route.paths.push(path);
8073 // Send payment with manually set total_msat
8074 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8075 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
8076 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();
8077 check_added_monitors!(nodes[src_idx], expected_paths.len());
8079 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8080 assert_eq!(events.len(), expected_paths.len());
8081 let mut amount_received = 0;
8082 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8083 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8085 let current_path_amount = msat_amounts[path_idx];
8086 amount_received += current_path_amount;
8087 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8088 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8091 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8095 fn test_overshoot_mpp() {
8096 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8097 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8101 fn test_simple_mpp() {
8102 // Simple test of sending a multi-path payment.
8103 let chanmon_cfgs = create_chanmon_cfgs(4);
8104 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8105 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8106 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8108 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8109 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8110 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8111 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8113 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8114 let path = route.paths[0].clone();
8115 route.paths.push(path);
8116 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8117 route.paths[0][0].short_channel_id = chan_1_id;
8118 route.paths[0][1].short_channel_id = chan_3_id;
8119 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8120 route.paths[1][0].short_channel_id = chan_2_id;
8121 route.paths[1][1].short_channel_id = chan_4_id;
8122 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8123 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8127 fn test_preimage_storage() {
8128 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8129 let chanmon_cfgs = create_chanmon_cfgs(2);
8130 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8132 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8134 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8137 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8138 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8139 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8140 check_added_monitors!(nodes[0], 1);
8141 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8142 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8143 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8144 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8146 // Note that after leaving the above scope we have no knowledge of any arguments or return
8147 // values from previous calls.
8148 expect_pending_htlcs_forwardable!(nodes[1]);
8149 let events = nodes[1].node.get_and_clear_pending_events();
8150 assert_eq!(events.len(), 1);
8152 Event::PaymentClaimable { ref purpose, .. } => {
8154 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8155 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8157 _ => panic!("expected PaymentPurpose::InvoicePayment")
8160 _ => panic!("Unexpected event"),
8165 #[allow(deprecated)]
8166 fn test_secret_timeout() {
8167 // Simple test of payment secret storage time outs. After
8168 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8169 let chanmon_cfgs = create_chanmon_cfgs(2);
8170 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8171 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8172 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8174 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8176 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8178 // We should fail to register the same payment hash twice, at least until we've connected a
8179 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8180 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8181 assert_eq!(err, "Duplicate payment hash");
8182 } else { panic!(); }
8184 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8186 header: BlockHeader {
8188 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8189 merkle_root: TxMerkleNode::all_zeros(),
8190 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8194 connect_block(&nodes[1], &block);
8195 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8196 assert_eq!(err, "Duplicate payment hash");
8197 } else { panic!(); }
8199 // If we then connect the second block, we should be able to register the same payment hash
8200 // again (this time getting a new payment secret).
8201 block.header.prev_blockhash = block.header.block_hash();
8202 block.header.time += 1;
8203 connect_block(&nodes[1], &block);
8204 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8205 assert_ne!(payment_secret_1, our_payment_secret);
8208 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8209 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8210 check_added_monitors!(nodes[0], 1);
8211 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8212 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8213 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8214 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8216 // Note that after leaving the above scope we have no knowledge of any arguments or return
8217 // values from previous calls.
8218 expect_pending_htlcs_forwardable!(nodes[1]);
8219 let events = nodes[1].node.get_and_clear_pending_events();
8220 assert_eq!(events.len(), 1);
8222 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8223 assert!(payment_preimage.is_none());
8224 assert_eq!(payment_secret, our_payment_secret);
8225 // We don't actually have the payment preimage with which to claim this payment!
8227 _ => panic!("Unexpected event"),
8232 fn test_bad_secret_hash() {
8233 // Simple test of unregistered payment hash/invalid payment secret handling
8234 let chanmon_cfgs = create_chanmon_cfgs(2);
8235 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8236 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8237 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8239 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8241 let random_payment_hash = PaymentHash([42; 32]);
8242 let random_payment_secret = PaymentSecret([43; 32]);
8243 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8244 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8246 // All the below cases should end up being handled exactly identically, so we macro the
8247 // resulting events.
8248 macro_rules! handle_unknown_invalid_payment_data {
8249 ($payment_hash: expr) => {
8250 check_added_monitors!(nodes[0], 1);
8251 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8252 let payment_event = SendEvent::from_event(events.pop().unwrap());
8253 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8254 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8256 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8257 // again to process the pending backwards-failure of the HTLC
8258 expect_pending_htlcs_forwardable!(nodes[1]);
8259 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8260 check_added_monitors!(nodes[1], 1);
8262 // We should fail the payment back
8263 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8264 match events.pop().unwrap() {
8265 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8266 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8267 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8269 _ => panic!("Unexpected event"),
8274 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8275 // Error data is the HTLC value (100,000) and current block height
8276 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8278 // Send a payment with the right payment hash but the wrong payment secret
8279 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8280 handle_unknown_invalid_payment_data!(our_payment_hash);
8281 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8283 // Send a payment with a random payment hash, but the right payment secret
8284 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8285 handle_unknown_invalid_payment_data!(random_payment_hash);
8286 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8288 // Send a payment with a random payment hash and random payment secret
8289 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8290 handle_unknown_invalid_payment_data!(random_payment_hash);
8291 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8295 fn test_update_err_monitor_lockdown() {
8296 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8297 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8298 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8301 // This scenario may happen in a watchtower setup, where watchtower process a block height
8302 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8303 // commitment at same time.
8305 let chanmon_cfgs = create_chanmon_cfgs(2);
8306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8308 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8310 // Create some initial channel
8311 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8312 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8314 // Rebalance the network to generate htlc in the two directions
8315 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8317 // Route a HTLC from node 0 to node 1 (but don't settle)
8318 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8320 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8321 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8322 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8323 let persister = test_utils::TestPersister::new();
8326 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8327 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8328 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8329 assert!(new_monitor == *monitor);
8332 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);
8333 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8336 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8337 let block = Block { header, txdata: vec![] };
8338 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8339 // transaction lock time requirements here.
8340 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8341 watchtower.chain_monitor.block_connected(&block, 200);
8343 // Try to update ChannelMonitor
8344 nodes[1].node.claim_funds(preimage);
8345 check_added_monitors!(nodes[1], 1);
8346 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8348 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8349 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8350 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8352 let mut node_0_per_peer_lock;
8353 let mut node_0_peer_state_lock;
8354 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8355 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8356 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8357 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8358 } else { assert!(false); }
8360 // Our local monitor is in-sync and hasn't processed yet timeout
8361 check_added_monitors!(nodes[0], 1);
8362 let events = nodes[0].node.get_and_clear_pending_events();
8363 assert_eq!(events.len(), 1);
8367 fn test_concurrent_monitor_claim() {
8368 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8369 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8370 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8371 // state N+1 confirms. Alice claims output from state N+1.
8373 let chanmon_cfgs = create_chanmon_cfgs(2);
8374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8376 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8378 // Create some initial channel
8379 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8380 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8382 // Rebalance the network to generate htlc in the two directions
8383 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8385 // Route a HTLC from node 0 to node 1 (but don't settle)
8386 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8388 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8389 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8390 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8391 let persister = test_utils::TestPersister::new();
8392 let watchtower_alice = {
8394 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8395 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8396 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8397 assert!(new_monitor == *monitor);
8400 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8401 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8404 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8405 let block = Block { header, txdata: vec![] };
8406 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8407 // transaction lock time requirements here.
8408 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));
8409 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8411 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8413 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8414 assert_eq!(txn.len(), 2);
8418 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8419 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8420 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8421 let persister = test_utils::TestPersister::new();
8422 let watchtower_bob = {
8424 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8425 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8426 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8427 assert!(new_monitor == *monitor);
8430 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);
8431 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8434 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8435 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8437 // Route another payment to generate another update with still previous HTLC pending
8438 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8440 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8442 check_added_monitors!(nodes[1], 1);
8444 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8445 assert_eq!(updates.update_add_htlcs.len(), 1);
8446 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8448 let mut node_0_per_peer_lock;
8449 let mut node_0_peer_state_lock;
8450 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8451 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8452 // Watchtower Alice should already have seen the block and reject the update
8453 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8454 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8455 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8456 } else { assert!(false); }
8458 // Our local monitor is in-sync and hasn't processed yet timeout
8459 check_added_monitors!(nodes[0], 1);
8461 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8462 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8463 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8465 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8468 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8469 assert_eq!(txn.len(), 2);
8470 bob_state_y = txn[0].clone();
8474 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8475 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8476 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);
8478 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8479 assert_eq!(htlc_txn.len(), 1);
8480 check_spends!(htlc_txn[0], bob_state_y);
8485 fn test_pre_lockin_no_chan_closed_update() {
8486 // Test that if a peer closes a channel in response to a funding_created message we don't
8487 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8490 // Doing so would imply a channel monitor update before the initial channel monitor
8491 // registration, violating our API guarantees.
8493 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8494 // then opening a second channel with the same funding output as the first (which is not
8495 // rejected because the first channel does not exist in the ChannelManager) and closing it
8496 // before receiving funding_signed.
8497 let chanmon_cfgs = create_chanmon_cfgs(2);
8498 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8499 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8500 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8502 // Create an initial channel
8503 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8504 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8505 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8506 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8507 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8509 // Move the first channel through the funding flow...
8510 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8512 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8513 check_added_monitors!(nodes[0], 0);
8515 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8516 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8517 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8518 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8519 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8523 fn test_htlc_no_detection() {
8524 // This test is a mutation to underscore the detection logic bug we had
8525 // before #653. HTLC value routed is above the remaining balance, thus
8526 // inverting HTLC and `to_remote` output. HTLC will come second and
8527 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8528 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8529 // outputs order detection for correct spending children filtring.
8531 let chanmon_cfgs = create_chanmon_cfgs(2);
8532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8534 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8536 // Create some initial channels
8537 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8539 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8540 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8541 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8542 assert_eq!(local_txn[0].input.len(), 1);
8543 assert_eq!(local_txn[0].output.len(), 3);
8544 check_spends!(local_txn[0], chan_1.3);
8546 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8547 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8548 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8549 // We deliberately connect the local tx twice as this should provoke a failure calling
8550 // this test before #653 fix.
8551 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);
8552 check_closed_broadcast!(nodes[0], true);
8553 check_added_monitors!(nodes[0], 1);
8554 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8555 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8557 let htlc_timeout = {
8558 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8559 assert_eq!(node_txn.len(), 1);
8560 assert_eq!(node_txn[0].input.len(), 1);
8561 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8562 check_spends!(node_txn[0], local_txn[0]);
8566 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8567 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8568 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8569 expect_payment_failed!(nodes[0], our_payment_hash, false);
8572 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8573 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8574 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8575 // Carol, Alice would be the upstream node, and Carol the downstream.)
8577 // Steps of the test:
8578 // 1) Alice sends a HTLC to Carol through Bob.
8579 // 2) Carol doesn't settle the HTLC.
8580 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8581 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8582 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8583 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8584 // 5) Carol release the preimage to Bob off-chain.
8585 // 6) Bob claims the offered output on the broadcasted commitment.
8586 let chanmon_cfgs = create_chanmon_cfgs(3);
8587 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8589 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8591 // Create some initial channels
8592 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8593 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8595 // Steps (1) and (2):
8596 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8597 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8599 // Check that Alice's commitment transaction now contains an output for this HTLC.
8600 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8601 check_spends!(alice_txn[0], chan_ab.3);
8602 assert_eq!(alice_txn[0].output.len(), 2);
8603 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8604 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8605 assert_eq!(alice_txn.len(), 2);
8607 // Steps (3) and (4):
8608 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8609 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8610 let mut force_closing_node = 0; // Alice force-closes
8611 let mut counterparty_node = 1; // Bob if Alice force-closes
8614 if !broadcast_alice {
8615 force_closing_node = 1;
8616 counterparty_node = 0;
8618 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8619 check_closed_broadcast!(nodes[force_closing_node], true);
8620 check_added_monitors!(nodes[force_closing_node], 1);
8621 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8622 if go_onchain_before_fulfill {
8623 let txn_to_broadcast = match broadcast_alice {
8624 true => alice_txn.clone(),
8625 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8627 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8628 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8629 if broadcast_alice {
8630 check_closed_broadcast!(nodes[1], true);
8631 check_added_monitors!(nodes[1], 1);
8632 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8637 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8638 // process of removing the HTLC from their commitment transactions.
8639 nodes[2].node.claim_funds(payment_preimage);
8640 check_added_monitors!(nodes[2], 1);
8641 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8643 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8644 assert!(carol_updates.update_add_htlcs.is_empty());
8645 assert!(carol_updates.update_fail_htlcs.is_empty());
8646 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8647 assert!(carol_updates.update_fee.is_none());
8648 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8650 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8651 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8652 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8653 if !go_onchain_before_fulfill && broadcast_alice {
8654 let events = nodes[1].node.get_and_clear_pending_msg_events();
8655 assert_eq!(events.len(), 1);
8657 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8658 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8660 _ => panic!("Unexpected event"),
8663 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8664 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8665 // Carol<->Bob's updated commitment transaction info.
8666 check_added_monitors!(nodes[1], 2);
8668 let events = nodes[1].node.get_and_clear_pending_msg_events();
8669 assert_eq!(events.len(), 2);
8670 let bob_revocation = match events[0] {
8671 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8672 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8675 _ => panic!("Unexpected event"),
8677 let bob_updates = match events[1] {
8678 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8679 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8682 _ => panic!("Unexpected event"),
8685 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8686 check_added_monitors!(nodes[2], 1);
8687 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8688 check_added_monitors!(nodes[2], 1);
8690 let events = nodes[2].node.get_and_clear_pending_msg_events();
8691 assert_eq!(events.len(), 1);
8692 let carol_revocation = match events[0] {
8693 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8694 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8697 _ => panic!("Unexpected event"),
8699 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8700 check_added_monitors!(nodes[1], 1);
8702 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8703 // here's where we put said channel's commitment tx on-chain.
8704 let mut txn_to_broadcast = alice_txn.clone();
8705 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8706 if !go_onchain_before_fulfill {
8707 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8708 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8709 // If Bob was the one to force-close, he will have already passed these checks earlier.
8710 if broadcast_alice {
8711 check_closed_broadcast!(nodes[1], true);
8712 check_added_monitors!(nodes[1], 1);
8713 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8715 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8716 if broadcast_alice {
8717 assert_eq!(bob_txn.len(), 1);
8718 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8720 assert_eq!(bob_txn.len(), 2);
8721 check_spends!(bob_txn[0], chan_ab.3);
8726 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8727 // broadcasted commitment transaction.
8729 let script_weight = match broadcast_alice {
8730 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8731 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8733 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8734 // Bob force-closed and broadcasts the commitment transaction along with a
8735 // HTLC-output-claiming transaction.
8736 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8737 if broadcast_alice {
8738 assert_eq!(bob_txn.len(), 1);
8739 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8740 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8742 assert_eq!(bob_txn.len(), 2);
8743 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8744 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8750 fn test_onchain_htlc_settlement_after_close() {
8751 do_test_onchain_htlc_settlement_after_close(true, true);
8752 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8753 do_test_onchain_htlc_settlement_after_close(true, false);
8754 do_test_onchain_htlc_settlement_after_close(false, false);
8758 fn test_duplicate_temporary_channel_id_from_different_peers() {
8759 // Tests that we can accept two different `OpenChannel` requests with the same
8760 // `temporary_channel_id`, as long as they are from different peers.
8761 let chanmon_cfgs = create_chanmon_cfgs(3);
8762 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8763 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8764 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8766 // Create an first channel channel
8767 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8768 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8770 // Create an second channel
8771 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8772 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8774 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8775 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8776 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8778 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8779 // `temporary_channel_id` as they are from different peers.
8780 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8782 let events = nodes[0].node.get_and_clear_pending_msg_events();
8783 assert_eq!(events.len(), 1);
8785 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8786 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8787 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8789 _ => panic!("Unexpected event"),
8793 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8795 let events = nodes[0].node.get_and_clear_pending_msg_events();
8796 assert_eq!(events.len(), 1);
8798 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8799 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8800 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8802 _ => panic!("Unexpected event"),
8808 fn test_duplicate_chan_id() {
8809 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8810 // already open we reject it and keep the old channel.
8812 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8813 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8814 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8815 // updating logic for the existing channel.
8816 let chanmon_cfgs = create_chanmon_cfgs(2);
8817 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8818 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8819 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8821 // Create an initial channel
8822 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8823 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8824 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8825 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()));
8827 // Try to create a second channel with the same temporary_channel_id as the first and check
8828 // that it is rejected.
8829 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8831 let events = nodes[1].node.get_and_clear_pending_msg_events();
8832 assert_eq!(events.len(), 1);
8834 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8835 // Technically, at this point, nodes[1] would be justified in thinking both the
8836 // first (valid) and second (invalid) channels are closed, given they both have
8837 // the same non-temporary channel_id. However, currently we do not, so we just
8838 // move forward with it.
8839 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8840 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8842 _ => panic!("Unexpected event"),
8846 // Move the first channel through the funding flow...
8847 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8849 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8850 check_added_monitors!(nodes[0], 0);
8852 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8853 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8855 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8856 assert_eq!(added_monitors.len(), 1);
8857 assert_eq!(added_monitors[0].0, funding_output);
8858 added_monitors.clear();
8860 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8862 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8864 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8865 let channel_id = funding_outpoint.to_channel_id();
8867 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8870 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8871 // Technically this is allowed by the spec, but we don't support it and there's little reason
8872 // to. Still, it shouldn't cause any other issues.
8873 open_chan_msg.temporary_channel_id = channel_id;
8874 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8876 let events = nodes[1].node.get_and_clear_pending_msg_events();
8877 assert_eq!(events.len(), 1);
8879 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8880 // Technically, at this point, nodes[1] would be justified in thinking both
8881 // channels are closed, but currently we do not, so we just move forward with it.
8882 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8883 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8885 _ => panic!("Unexpected event"),
8889 // Now try to create a second channel which has a duplicate funding output.
8890 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8891 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8892 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8893 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()));
8894 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8896 let funding_created = {
8897 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8898 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8899 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8900 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8901 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8902 // channelmanager in a possibly nonsense state instead).
8903 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8904 let logger = test_utils::TestLogger::new();
8905 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8907 check_added_monitors!(nodes[0], 0);
8908 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8909 // At this point we'll look up if the channel_id is present and immediately fail the channel
8910 // without trying to persist the `ChannelMonitor`.
8911 check_added_monitors!(nodes[1], 0);
8913 // ...still, nodes[1] will reject the duplicate channel.
8915 let events = nodes[1].node.get_and_clear_pending_msg_events();
8916 assert_eq!(events.len(), 1);
8918 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8919 // Technically, at this point, nodes[1] would be justified in thinking both
8920 // channels are closed, but currently we do not, so we just move forward with it.
8921 assert_eq!(msg.channel_id, channel_id);
8922 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8924 _ => panic!("Unexpected event"),
8928 // finally, finish creating the original channel and send a payment over it to make sure
8929 // everything is functional.
8930 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8932 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8933 assert_eq!(added_monitors.len(), 1);
8934 assert_eq!(added_monitors[0].0, funding_output);
8935 added_monitors.clear();
8937 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8939 let events_4 = nodes[0].node.get_and_clear_pending_events();
8940 assert_eq!(events_4.len(), 0);
8941 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8942 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8944 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8945 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8946 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8948 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8952 fn test_error_chans_closed() {
8953 // Test that we properly handle error messages, closing appropriate channels.
8955 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8956 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8957 // we can test various edge cases around it to ensure we don't regress.
8958 let chanmon_cfgs = create_chanmon_cfgs(3);
8959 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8960 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8961 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8963 // Create some initial channels
8964 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8965 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8966 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8968 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8969 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8970 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8972 // Closing a channel from a different peer has no effect
8973 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8974 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8976 // Closing one channel doesn't impact others
8977 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8978 check_added_monitors!(nodes[0], 1);
8979 check_closed_broadcast!(nodes[0], false);
8980 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8981 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8982 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8983 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);
8984 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);
8986 // A null channel ID should close all channels
8987 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8988 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8989 check_added_monitors!(nodes[0], 2);
8990 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8991 let events = nodes[0].node.get_and_clear_pending_msg_events();
8992 assert_eq!(events.len(), 2);
8994 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8995 assert_eq!(msg.contents.flags & 2, 2);
8997 _ => panic!("Unexpected event"),
9000 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9001 assert_eq!(msg.contents.flags & 2, 2);
9003 _ => panic!("Unexpected event"),
9005 // Note that at this point users of a standard PeerHandler will end up calling
9006 // peer_disconnected.
9007 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9008 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9010 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9011 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9012 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9016 fn test_invalid_funding_tx() {
9017 // Test that we properly handle invalid funding transactions sent to us from a peer.
9019 // Previously, all other major lightning implementations had failed to properly sanitize
9020 // funding transactions from their counterparties, leading to a multi-implementation critical
9021 // security vulnerability (though we always sanitized properly, we've previously had
9022 // un-released crashes in the sanitization process).
9024 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9025 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9026 // gave up on it. We test this here by generating such a transaction.
9027 let chanmon_cfgs = create_chanmon_cfgs(2);
9028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9030 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9032 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9033 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()));
9034 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()));
9036 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9038 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9039 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9040 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9042 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9043 let wit_program_script: Script = wit_program.into();
9044 for output in tx.output.iter_mut() {
9045 // Make the confirmed funding transaction have a bogus script_pubkey
9046 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9049 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9050 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()));
9051 check_added_monitors!(nodes[1], 1);
9052 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9054 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()));
9055 check_added_monitors!(nodes[0], 1);
9056 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9058 let events_1 = nodes[0].node.get_and_clear_pending_events();
9059 assert_eq!(events_1.len(), 0);
9061 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9062 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9063 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9065 let expected_err = "funding tx had wrong script/value or output index";
9066 confirm_transaction_at(&nodes[1], &tx, 1);
9067 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9068 check_added_monitors!(nodes[1], 1);
9069 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9070 assert_eq!(events_2.len(), 1);
9071 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9072 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9073 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9074 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9075 } else { panic!(); }
9076 } else { panic!(); }
9077 assert_eq!(nodes[1].node.list_channels().len(), 0);
9079 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9080 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9081 // as its not 32 bytes long.
9082 let mut spend_tx = Transaction {
9083 version: 2i32, lock_time: PackedLockTime::ZERO,
9084 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9085 previous_output: BitcoinOutPoint {
9089 script_sig: Script::new(),
9090 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9091 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9093 output: vec![TxOut {
9095 script_pubkey: Script::new(),
9098 check_spends!(spend_tx, tx);
9099 mine_transaction(&nodes[1], &spend_tx);
9102 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9103 // In the first version of the chain::Confirm interface, after a refactor was made to not
9104 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9105 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9106 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9107 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9108 // spending transaction until height N+1 (or greater). This was due to the way
9109 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9110 // spending transaction at the height the input transaction was confirmed at, not whether we
9111 // should broadcast a spending transaction at the current height.
9112 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9113 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9114 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9115 // until we learned about an additional block.
9117 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9118 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9119 let chanmon_cfgs = create_chanmon_cfgs(3);
9120 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9121 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9122 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9123 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9125 create_announced_chan_between_nodes(&nodes, 0, 1);
9126 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9127 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9128 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9129 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9131 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9132 check_closed_broadcast!(nodes[1], true);
9133 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9134 check_added_monitors!(nodes[1], 1);
9135 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9136 assert_eq!(node_txn.len(), 1);
9138 let conf_height = nodes[1].best_block_info().1;
9139 if !test_height_before_timelock {
9140 connect_blocks(&nodes[1], 24 * 6);
9142 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9143 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9144 if test_height_before_timelock {
9145 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9146 // generate any events or broadcast any transactions
9147 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9148 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9150 // We should broadcast an HTLC transaction spending our funding transaction first
9151 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9152 assert_eq!(spending_txn.len(), 2);
9153 assert_eq!(spending_txn[0], node_txn[0]);
9154 check_spends!(spending_txn[1], node_txn[0]);
9155 // We should also generate a SpendableOutputs event with the to_self output (as its
9157 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9158 assert_eq!(descriptor_spend_txn.len(), 1);
9160 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9161 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9162 // additional block built on top of the current chain.
9163 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9164 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9165 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 }]);
9166 check_added_monitors!(nodes[1], 1);
9168 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9169 assert!(updates.update_add_htlcs.is_empty());
9170 assert!(updates.update_fulfill_htlcs.is_empty());
9171 assert_eq!(updates.update_fail_htlcs.len(), 1);
9172 assert!(updates.update_fail_malformed_htlcs.is_empty());
9173 assert!(updates.update_fee.is_none());
9174 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9175 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9176 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9181 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9182 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9183 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9186 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9187 let chanmon_cfgs = create_chanmon_cfgs(2);
9188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9190 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9192 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9194 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9195 .with_features(nodes[1].node.invoice_features());
9196 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9198 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9201 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9202 check_added_monitors!(nodes[0], 1);
9203 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9204 assert_eq!(events.len(), 1);
9205 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9206 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9207 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9209 expect_pending_htlcs_forwardable!(nodes[1]);
9210 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9213 // Note that we use a different PaymentId here to allow us to duplicativly pay
9214 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9215 check_added_monitors!(nodes[0], 1);
9216 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9217 assert_eq!(events.len(), 1);
9218 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9219 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9220 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9221 // At this point, nodes[1] would notice it has too much value for the payment. It will
9222 // assume the second is a privacy attack (no longer particularly relevant
9223 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9224 // the first HTLC delivered above.
9227 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9228 nodes[1].node.process_pending_htlc_forwards();
9230 if test_for_second_fail_panic {
9231 // Now we go fail back the first HTLC from the user end.
9232 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9234 let expected_destinations = vec![
9235 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9236 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9238 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9239 nodes[1].node.process_pending_htlc_forwards();
9241 check_added_monitors!(nodes[1], 1);
9242 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9243 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9246 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9247 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9249 let failure_events = nodes[0].node.get_and_clear_pending_events();
9250 assert_eq!(failure_events.len(), 4);
9251 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9252 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9253 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9254 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9256 // Let the second HTLC fail and claim the first
9257 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9258 nodes[1].node.process_pending_htlc_forwards();
9260 check_added_monitors!(nodes[1], 1);
9261 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9262 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9263 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9265 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9267 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9272 fn test_dup_htlc_second_fail_panic() {
9273 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9274 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9275 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9276 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9277 do_test_dup_htlc_second_rejected(true);
9281 fn test_dup_htlc_second_rejected() {
9282 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9283 // simply reject the second HTLC but are still able to claim the first HTLC.
9284 do_test_dup_htlc_second_rejected(false);
9288 fn test_inconsistent_mpp_params() {
9289 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9290 // such HTLC and allow the second to stay.
9291 let chanmon_cfgs = create_chanmon_cfgs(4);
9292 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9293 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9294 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9296 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9297 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9298 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9299 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9301 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9302 .with_features(nodes[3].node.invoice_features());
9303 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9304 assert_eq!(route.paths.len(), 2);
9305 route.paths.sort_by(|path_a, _| {
9306 // Sort the path so that the path through nodes[1] comes first
9307 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9308 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9311 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9313 let cur_height = nodes[0].best_block_info().1;
9314 let payment_id = PaymentId([42; 32]);
9316 let session_privs = {
9317 // We create a fake route here so that we start with three pending HTLCs, which we'll
9318 // ultimately have, just not right away.
9319 let mut dup_route = route.clone();
9320 dup_route.paths.push(route.paths[1].clone());
9321 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9323 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();
9324 check_added_monitors!(nodes[0], 1);
9327 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9328 assert_eq!(events.len(), 1);
9329 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9331 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9333 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();
9334 check_added_monitors!(nodes[0], 1);
9337 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9338 assert_eq!(events.len(), 1);
9339 let payment_event = SendEvent::from_event(events.pop().unwrap());
9341 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9342 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9344 expect_pending_htlcs_forwardable!(nodes[2]);
9345 check_added_monitors!(nodes[2], 1);
9347 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9348 assert_eq!(events.len(), 1);
9349 let payment_event = SendEvent::from_event(events.pop().unwrap());
9351 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9352 check_added_monitors!(nodes[3], 0);
9353 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9355 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9356 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9357 // post-payment_secrets) and fail back the new HTLC.
9359 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9360 nodes[3].node.process_pending_htlc_forwards();
9361 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9362 nodes[3].node.process_pending_htlc_forwards();
9364 check_added_monitors!(nodes[3], 1);
9366 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9367 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9368 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9370 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 }]);
9371 check_added_monitors!(nodes[2], 1);
9373 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9374 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9375 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9377 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9379 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();
9380 check_added_monitors!(nodes[0], 1);
9382 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9383 assert_eq!(events.len(), 1);
9384 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9386 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9387 let events = nodes[0].node.get_and_clear_pending_events();
9388 assert_eq!(events.len(), 3);
9390 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9391 assert_eq!(payment_hash, our_payment_hash);
9393 _ => panic!("Unexpected event")
9396 Event::PaymentPathSuccessful { payment_hash, .. } => {
9397 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9399 _ => panic!("Unexpected event")
9402 Event::PaymentPathSuccessful { payment_hash, .. } => {
9403 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9405 _ => panic!("Unexpected event")
9410 fn test_keysend_payments_to_public_node() {
9411 let chanmon_cfgs = create_chanmon_cfgs(2);
9412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9414 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9416 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9417 let network_graph = nodes[0].network_graph.clone();
9418 let payer_pubkey = nodes[0].node.get_our_node_id();
9419 let payee_pubkey = nodes[1].node.get_our_node_id();
9420 let route_params = RouteParameters {
9421 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9422 final_value_msat: 10000,
9424 let scorer = test_utils::TestScorer::new();
9425 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9426 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9428 let test_preimage = PaymentPreimage([42; 32]);
9429 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9430 check_added_monitors!(nodes[0], 1);
9431 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9432 assert_eq!(events.len(), 1);
9433 let event = events.pop().unwrap();
9434 let path = vec![&nodes[1]];
9435 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9436 claim_payment(&nodes[0], &path, test_preimage);
9440 fn test_keysend_payments_to_private_node() {
9441 let chanmon_cfgs = create_chanmon_cfgs(2);
9442 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9443 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9444 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9446 let payer_pubkey = nodes[0].node.get_our_node_id();
9447 let payee_pubkey = nodes[1].node.get_our_node_id();
9449 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9450 let route_params = RouteParameters {
9451 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9452 final_value_msat: 10000,
9454 let network_graph = nodes[0].network_graph.clone();
9455 let first_hops = nodes[0].node.list_usable_channels();
9456 let scorer = test_utils::TestScorer::new();
9457 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9458 let route = find_route(
9459 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9460 nodes[0].logger, &scorer, &random_seed_bytes
9463 let test_preimage = PaymentPreimage([42; 32]);
9464 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9465 check_added_monitors!(nodes[0], 1);
9466 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9467 assert_eq!(events.len(), 1);
9468 let event = events.pop().unwrap();
9469 let path = vec![&nodes[1]];
9470 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9471 claim_payment(&nodes[0], &path, test_preimage);
9475 fn test_double_partial_claim() {
9476 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9477 // time out, the sender resends only some of the MPP parts, then the user processes the
9478 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9480 let chanmon_cfgs = create_chanmon_cfgs(4);
9481 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9482 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9483 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9485 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9486 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9487 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9488 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9490 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9491 assert_eq!(route.paths.len(), 2);
9492 route.paths.sort_by(|path_a, _| {
9493 // Sort the path so that the path through nodes[1] comes first
9494 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9495 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9498 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9499 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9500 // amount of time to respond to.
9502 // Connect some blocks to time out the payment
9503 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9504 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9506 let failed_destinations = vec![
9507 HTLCDestination::FailedPayment { payment_hash },
9508 HTLCDestination::FailedPayment { payment_hash },
9510 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9512 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9514 // nodes[1] now retries one of the two paths...
9515 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9516 check_added_monitors!(nodes[0], 2);
9518 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9519 assert_eq!(events.len(), 2);
9520 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9521 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9523 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9524 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9525 nodes[3].node.claim_funds(payment_preimage);
9526 check_added_monitors!(nodes[3], 0);
9527 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9530 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9531 #[derive(Clone, Copy, PartialEq)]
9532 enum ExposureEvent {
9533 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9535 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9537 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9538 AtUpdateFeeOutbound,
9541 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9542 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9545 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9546 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9547 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9548 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9549 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9550 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9551 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9552 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9554 let chanmon_cfgs = create_chanmon_cfgs(2);
9555 let mut config = test_default_channel_config();
9556 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9559 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9561 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9562 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9563 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9564 open_channel.max_accepted_htlcs = 60;
9566 open_channel.dust_limit_satoshis = 546;
9568 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9569 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9570 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9572 let opt_anchors = false;
9574 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9577 let mut node_0_per_peer_lock;
9578 let mut node_0_peer_state_lock;
9579 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9580 chan.holder_dust_limit_satoshis = 546;
9583 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9584 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()));
9585 check_added_monitors!(nodes[1], 1);
9586 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9588 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()));
9589 check_added_monitors!(nodes[0], 1);
9590 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9592 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9593 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9594 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9596 let dust_buffer_feerate = {
9597 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9598 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9599 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9600 chan.get_dust_buffer_feerate(None) as u64
9602 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;
9603 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9605 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;
9606 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9608 let dust_htlc_on_counterparty_tx: u64 = 25;
9609 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9612 if dust_outbound_balance {
9613 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9614 // Outbound dust balance: 4372 sats
9615 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9616 for i in 0..dust_outbound_htlc_on_holder_tx {
9617 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9618 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); }
9621 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9622 // Inbound dust balance: 4372 sats
9623 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9624 for _ in 0..dust_inbound_htlc_on_holder_tx {
9625 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9629 if dust_outbound_balance {
9630 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9631 // Outbound dust balance: 5000 sats
9632 for i in 0..dust_htlc_on_counterparty_tx {
9633 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9634 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); }
9637 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9638 // Inbound dust balance: 5000 sats
9639 for _ in 0..dust_htlc_on_counterparty_tx {
9640 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9645 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9646 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9647 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 });
9648 let mut config = UserConfig::default();
9649 // With default dust exposure: 5000 sats
9651 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9652 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9653 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)));
9655 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)));
9657 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9658 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 });
9659 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9660 check_added_monitors!(nodes[1], 1);
9661 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9662 assert_eq!(events.len(), 1);
9663 let payment_event = SendEvent::from_event(events.remove(0));
9664 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9665 // With default dust exposure: 5000 sats
9667 // Outbound dust balance: 6399 sats
9668 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9669 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9670 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);
9672 // Outbound dust balance: 5200 sats
9673 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);
9675 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9676 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9677 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", ); }
9679 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9680 *feerate_lock = *feerate_lock * 10;
9682 nodes[0].node.timer_tick_occurred();
9683 check_added_monitors!(nodes[0], 1);
9684 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9687 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9688 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9689 added_monitors.clear();
9693 fn test_max_dust_htlc_exposure() {
9694 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9695 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9696 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9697 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9698 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9699 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9700 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9701 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9702 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9703 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9704 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9705 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9709 fn test_non_final_funding_tx() {
9710 let chanmon_cfgs = create_chanmon_cfgs(2);
9711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9715 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9716 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9717 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9718 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9719 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9721 let best_height = nodes[0].node.best_block.read().unwrap().height();
9723 let chan_id = *nodes[0].network_chan_count.borrow();
9724 let events = nodes[0].node.get_and_clear_pending_events();
9725 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9726 assert_eq!(events.len(), 1);
9727 let mut tx = match events[0] {
9728 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9729 // Timelock the transaction _beyond_ the best client height + 2.
9730 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9731 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9734 _ => panic!("Unexpected event"),
9736 // Transaction should fail as it's evaluated as non-final for propagation.
9737 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9738 Err(APIError::APIMisuseError { err }) => {
9739 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9744 // However, transaction should be accepted if it's in a +2 headroom from best block.
9745 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9746 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9747 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9751 fn accept_busted_but_better_fee() {
9752 // If a peer sends us a fee update that is too low, but higher than our previous channel
9753 // feerate, we should accept it. In the future we may want to consider closing the channel
9754 // later, but for now we only accept the update.
9755 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9756 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9757 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9758 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9760 create_chan_between_nodes(&nodes[0], &nodes[1]);
9762 // Set nodes[1] to expect 5,000 sat/kW.
9764 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9765 *feerate_lock = 5000;
9768 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9770 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9771 *feerate_lock = 1000;
9773 nodes[0].node.timer_tick_occurred();
9774 check_added_monitors!(nodes[0], 1);
9776 let events = nodes[0].node.get_and_clear_pending_msg_events();
9777 assert_eq!(events.len(), 1);
9779 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9780 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9781 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9783 _ => panic!("Unexpected event"),
9786 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9789 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9790 *feerate_lock = 2000;
9792 nodes[0].node.timer_tick_occurred();
9793 check_added_monitors!(nodes[0], 1);
9795 let events = nodes[0].node.get_and_clear_pending_msg_events();
9796 assert_eq!(events.len(), 1);
9798 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9799 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9800 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9802 _ => panic!("Unexpected event"),
9805 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9808 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9809 *feerate_lock = 1000;
9811 nodes[0].node.timer_tick_occurred();
9812 check_added_monitors!(nodes[0], 1);
9814 let events = nodes[0].node.get_and_clear_pending_msg_events();
9815 assert_eq!(events.len(), 1);
9817 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9818 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9819 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9820 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9821 check_closed_broadcast!(nodes[1], true);
9822 check_added_monitors!(nodes[1], 1);
9824 _ => panic!("Unexpected event"),
9828 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9829 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9833 let min_final_cltv_expiry_delta = 120;
9834 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9835 min_final_cltv_expiry_delta - 2 };
9836 let recv_value = 100_000;
9838 create_chan_between_nodes(&nodes[0], &nodes[1]);
9840 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9841 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9842 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9843 Some(recv_value), Some(min_final_cltv_expiry_delta));
9844 (payment_hash, payment_preimage, payment_secret)
9846 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9847 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9849 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9850 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9851 check_added_monitors!(nodes[0], 1);
9852 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9853 assert_eq!(events.len(), 1);
9854 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9855 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9856 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9857 expect_pending_htlcs_forwardable!(nodes[1]);
9860 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9861 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9863 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9865 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9867 check_added_monitors!(nodes[1], 1);
9869 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9870 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9871 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9873 expect_payment_failed!(nodes[0], payment_hash, true);
9878 fn test_payment_with_custom_min_cltv_expiry_delta() {
9879 do_payment_with_custom_min_final_cltv_expiry(false, false);
9880 do_payment_with_custom_min_final_cltv_expiry(false, true);
9881 do_payment_with_custom_min_final_cltv_expiry(true, false);
9882 do_payment_with_custom_min_final_cltv_expiry(true, true);