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 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
546 if steps & 0x0f == 5 { return; }
547 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
549 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550 assert_eq!(added_monitors.len(), 1);
551 assert_eq!(added_monitors[0].0, funding_output);
552 added_monitors.clear();
555 let events_4 = nodes[0].node.get_and_clear_pending_events();
556 assert_eq!(events_4.len(), 0);
558 if steps & 0x0f == 6 { return; }
559 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
561 if steps & 0x0f == 7 { return; }
562 confirm_transaction_at(&nodes[0], &tx, 2);
563 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
564 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
565 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
569 fn test_sanity_on_in_flight_opens() {
570 do_test_sanity_on_in_flight_opens(0);
571 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
572 do_test_sanity_on_in_flight_opens(1);
573 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
574 do_test_sanity_on_in_flight_opens(2);
575 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
576 do_test_sanity_on_in_flight_opens(3);
577 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
578 do_test_sanity_on_in_flight_opens(4);
579 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
580 do_test_sanity_on_in_flight_opens(5);
581 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
582 do_test_sanity_on_in_flight_opens(6);
583 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
584 do_test_sanity_on_in_flight_opens(7);
585 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
586 do_test_sanity_on_in_flight_opens(8);
587 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
591 fn test_update_fee_vanilla() {
592 let chanmon_cfgs = create_chanmon_cfgs(2);
593 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
594 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
595 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
596 create_announced_chan_between_nodes(&nodes, 0, 1);
599 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
602 nodes[0].node.timer_tick_occurred();
603 check_added_monitors!(nodes[0], 1);
605 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
606 assert_eq!(events_0.len(), 1);
607 let (update_msg, commitment_signed) = match events_0[0] {
608 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 } } => {
609 (update_fee.as_ref(), commitment_signed)
611 _ => panic!("Unexpected event"),
613 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
615 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
616 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
617 check_added_monitors!(nodes[1], 1);
619 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
620 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
621 check_added_monitors!(nodes[0], 1);
623 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
624 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
625 // No commitment_signed so get_event_msg's assert(len == 1) passes
626 check_added_monitors!(nodes[0], 1);
628 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
629 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
630 check_added_monitors!(nodes[1], 1);
634 fn test_update_fee_that_funder_cannot_afford() {
635 let chanmon_cfgs = create_chanmon_cfgs(2);
636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
638 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
639 let channel_value = 5000;
641 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
642 let channel_id = chan.2;
643 let secp_ctx = Secp256k1::new();
644 let default_config = UserConfig::default();
645 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
647 let opt_anchors = false;
649 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
650 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
651 // calculate two different feerates here - the expected local limit as well as the expected
653 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;
654 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
656 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
657 *feerate_lock = feerate;
659 nodes[0].node.timer_tick_occurred();
660 check_added_monitors!(nodes[0], 1);
661 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
663 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
665 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
667 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
669 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
671 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
672 assert_eq!(commitment_tx.output.len(), 2);
673 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
674 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
675 actual_fee = channel_value - actual_fee;
676 assert_eq!(total_fee, actual_fee);
680 // Increment the feerate by a small constant, accounting for rounding errors
681 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
684 nodes[0].node.timer_tick_occurred();
685 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
686 check_added_monitors!(nodes[0], 0);
688 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
690 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
691 // needed to sign the new commitment tx and (2) sign the new commitment tx.
692 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
693 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
694 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
695 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
696 let chan_signer = local_chan.get_signer();
697 let pubkeys = chan_signer.pubkeys();
698 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
699 pubkeys.funding_pubkey)
701 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
702 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
703 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
704 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
705 let chan_signer = remote_chan.get_signer();
706 let pubkeys = chan_signer.pubkeys();
707 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
708 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
709 pubkeys.funding_pubkey)
712 // Assemble the set of keys we can use for signatures for our commitment_signed message.
713 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
714 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
717 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
718 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
719 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
720 let local_chan_signer = local_chan.get_signer();
721 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
722 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
723 INITIAL_COMMITMENT_NUMBER - 1,
725 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
726 opt_anchors, local_funding, remote_funding,
727 commit_tx_keys.clone(),
728 non_buffer_feerate + 4,
730 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
732 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
735 let commit_signed_msg = msgs::CommitmentSigned {
738 htlc_signatures: res.1,
740 partial_signature_with_nonce: None,
743 let update_fee = msgs::UpdateFee {
745 feerate_per_kw: non_buffer_feerate + 4,
748 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
750 //While producing the commitment_signed response after handling a received update_fee request the
751 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
752 //Should produce and error.
753 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
754 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
755 check_added_monitors!(nodes[1], 1);
756 check_closed_broadcast!(nodes[1], true);
757 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
761 fn test_update_fee_with_fundee_update_add_htlc() {
762 let chanmon_cfgs = create_chanmon_cfgs(2);
763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
765 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
766 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
769 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
772 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
775 nodes[0].node.timer_tick_occurred();
776 check_added_monitors!(nodes[0], 1);
778 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
779 assert_eq!(events_0.len(), 1);
780 let (update_msg, commitment_signed) = match events_0[0] {
781 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 } } => {
782 (update_fee.as_ref(), commitment_signed)
784 _ => panic!("Unexpected event"),
786 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
787 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
788 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
789 check_added_monitors!(nodes[1], 1);
791 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
793 // nothing happens since node[1] is in AwaitingRemoteRevoke
794 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
796 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
797 assert_eq!(added_monitors.len(), 0);
798 added_monitors.clear();
800 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
801 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
802 // node[1] has nothing to do
804 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
805 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
806 check_added_monitors!(nodes[0], 1);
808 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
809 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
810 // No commitment_signed so get_event_msg's assert(len == 1) passes
811 check_added_monitors!(nodes[0], 1);
812 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
813 check_added_monitors!(nodes[1], 1);
814 // AwaitingRemoteRevoke ends here
816 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
817 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
818 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
819 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
820 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fee.is_none(), true);
823 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
824 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
825 check_added_monitors!(nodes[0], 1);
826 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
828 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
829 check_added_monitors!(nodes[1], 1);
830 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
832 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
833 check_added_monitors!(nodes[1], 1);
834 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
835 // No commitment_signed so get_event_msg's assert(len == 1) passes
837 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
838 check_added_monitors!(nodes[0], 1);
839 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
841 expect_pending_htlcs_forwardable!(nodes[0]);
843 let events = nodes[0].node.get_and_clear_pending_events();
844 assert_eq!(events.len(), 1);
846 Event::PaymentClaimable { .. } => { },
847 _ => panic!("Unexpected event"),
850 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
852 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
853 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
854 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
855 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
856 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
860 fn test_update_fee() {
861 let chanmon_cfgs = create_chanmon_cfgs(2);
862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
864 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
865 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
866 let channel_id = chan.2;
869 // (1) update_fee/commitment_signed ->
870 // <- (2) revoke_and_ack
871 // .- send (3) commitment_signed
872 // (4) update_fee/commitment_signed ->
873 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
874 // <- (3) commitment_signed delivered
875 // send (6) revoke_and_ack -.
876 // <- (5) deliver revoke_and_ack
877 // (6) deliver revoke_and_ack ->
878 // .- send (7) commitment_signed in response to (4)
879 // <- (7) deliver commitment_signed
882 // Create and deliver (1)...
885 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
886 feerate = *feerate_lock;
887 *feerate_lock = feerate + 20;
889 nodes[0].node.timer_tick_occurred();
890 check_added_monitors!(nodes[0], 1);
892 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
893 assert_eq!(events_0.len(), 1);
894 let (update_msg, commitment_signed) = match events_0[0] {
895 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 } } => {
896 (update_fee.as_ref(), commitment_signed)
898 _ => panic!("Unexpected event"),
900 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
902 // Generate (2) and (3):
903 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
904 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
905 check_added_monitors!(nodes[1], 1);
908 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
909 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
910 check_added_monitors!(nodes[0], 1);
912 // Create and deliver (4)...
914 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
915 *feerate_lock = feerate + 30;
917 nodes[0].node.timer_tick_occurred();
918 check_added_monitors!(nodes[0], 1);
919 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
920 assert_eq!(events_0.len(), 1);
921 let (update_msg, commitment_signed) = match events_0[0] {
922 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 } } => {
923 (update_fee.as_ref(), commitment_signed)
925 _ => panic!("Unexpected event"),
928 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
929 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
930 check_added_monitors!(nodes[1], 1);
932 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
933 // No commitment_signed so get_event_msg's assert(len == 1) passes
935 // Handle (3), creating (6):
936 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
937 check_added_monitors!(nodes[0], 1);
938 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
939 // No commitment_signed so get_event_msg's assert(len == 1) passes
942 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
943 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
944 check_added_monitors!(nodes[0], 1);
946 // Deliver (6), creating (7):
947 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
948 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
949 assert!(commitment_update.update_add_htlcs.is_empty());
950 assert!(commitment_update.update_fulfill_htlcs.is_empty());
951 assert!(commitment_update.update_fail_htlcs.is_empty());
952 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
953 assert!(commitment_update.update_fee.is_none());
954 check_added_monitors!(nodes[1], 1);
957 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
958 check_added_monitors!(nodes[0], 1);
959 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
960 // No commitment_signed so get_event_msg's assert(len == 1) passes
962 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
963 check_added_monitors!(nodes[1], 1);
964 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
966 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
967 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
968 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
969 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
970 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
974 fn fake_network_test() {
975 // Simple test which builds a network of ChannelManagers, connects them to each other, and
976 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
977 let chanmon_cfgs = create_chanmon_cfgs(4);
978 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
979 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
980 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
982 // Create some initial channels
983 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
984 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
985 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
987 // Rebalance the network a bit by relaying one payment through all the channels...
988 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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);
993 // Send some more payments
994 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
995 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
996 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
998 // Test failure packets
999 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1000 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1002 // Add a new channel that skips 3
1003 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1005 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1006 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1007 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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);
1013 // Do some rebalance loop payments, simultaneously
1014 let mut hops = Vec::with_capacity(3);
1015 hops.push(RouteHop {
1016 pubkey: nodes[2].node.get_our_node_id(),
1017 node_features: NodeFeatures::empty(),
1018 short_channel_id: chan_2.0.contents.short_channel_id,
1019 channel_features: ChannelFeatures::empty(),
1021 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1023 hops.push(RouteHop {
1024 pubkey: nodes[3].node.get_our_node_id(),
1025 node_features: NodeFeatures::empty(),
1026 short_channel_id: chan_3.0.contents.short_channel_id,
1027 channel_features: ChannelFeatures::empty(),
1029 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1031 hops.push(RouteHop {
1032 pubkey: nodes[1].node.get_our_node_id(),
1033 node_features: nodes[1].node.node_features(),
1034 short_channel_id: chan_4.0.contents.short_channel_id,
1035 channel_features: nodes[1].node.channel_features(),
1037 cltv_expiry_delta: TEST_FINAL_CLTV,
1039 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;
1040 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;
1041 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;
1043 let mut hops = Vec::with_capacity(3);
1044 hops.push(RouteHop {
1045 pubkey: nodes[3].node.get_our_node_id(),
1046 node_features: NodeFeatures::empty(),
1047 short_channel_id: chan_4.0.contents.short_channel_id,
1048 channel_features: ChannelFeatures::empty(),
1050 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1052 hops.push(RouteHop {
1053 pubkey: nodes[2].node.get_our_node_id(),
1054 node_features: NodeFeatures::empty(),
1055 short_channel_id: chan_3.0.contents.short_channel_id,
1056 channel_features: ChannelFeatures::empty(),
1058 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1060 hops.push(RouteHop {
1061 pubkey: nodes[1].node.get_our_node_id(),
1062 node_features: nodes[1].node.node_features(),
1063 short_channel_id: chan_2.0.contents.short_channel_id,
1064 channel_features: nodes[1].node.channel_features(),
1066 cltv_expiry_delta: TEST_FINAL_CLTV,
1068 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;
1069 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;
1070 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;
1072 // Claim the rebalances...
1073 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1074 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1076 // Close down the channels...
1077 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1078 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1079 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1080 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1083 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1086 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1087 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092 fn holding_cell_htlc_counting() {
1093 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1094 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1095 // commitment dance rounds.
1096 let chanmon_cfgs = create_chanmon_cfgs(3);
1097 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1098 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1099 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1100 create_announced_chan_between_nodes(&nodes, 0, 1);
1101 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1103 let mut payments = Vec::new();
1104 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1105 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1106 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1107 payments.push((payment_preimage, payment_hash));
1109 check_added_monitors!(nodes[1], 1);
1111 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1112 assert_eq!(events.len(), 1);
1113 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1114 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1116 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1117 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1119 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1121 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 },
1122 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1123 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1124 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1127 // This should also be true if we try to forward a payment.
1128 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1130 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1131 check_added_monitors!(nodes[0], 1);
1134 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1135 assert_eq!(events.len(), 1);
1136 let payment_event = SendEvent::from_event(events.pop().unwrap());
1137 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1139 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1140 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1141 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1142 // fails), the second will process the resulting failure and fail the HTLC backward.
1143 expect_pending_htlcs_forwardable!(nodes[1]);
1144 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 }]);
1145 check_added_monitors!(nodes[1], 1);
1147 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1148 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1149 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1151 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1153 // Now forward all the pending HTLCs and claim them back
1154 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1155 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1156 check_added_monitors!(nodes[2], 1);
1158 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1159 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1160 check_added_monitors!(nodes[1], 1);
1161 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1163 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1164 check_added_monitors!(nodes[1], 1);
1165 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1167 for ref update in as_updates.update_add_htlcs.iter() {
1168 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1170 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1171 check_added_monitors!(nodes[2], 1);
1172 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1173 check_added_monitors!(nodes[2], 1);
1174 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1176 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1177 check_added_monitors!(nodes[1], 1);
1178 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1179 check_added_monitors!(nodes[1], 1);
1180 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1182 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1183 check_added_monitors!(nodes[2], 1);
1185 expect_pending_htlcs_forwardable!(nodes[2]);
1187 let events = nodes[2].node.get_and_clear_pending_events();
1188 assert_eq!(events.len(), payments.len());
1189 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1191 &Event::PaymentClaimable { ref payment_hash, .. } => {
1192 assert_eq!(*payment_hash, *hash);
1194 _ => panic!("Unexpected event"),
1198 for (preimage, _) in payments.drain(..) {
1199 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1202 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1206 fn duplicate_htlc_test() {
1207 // Test that we accept duplicate payment_hash HTLCs across the network and that
1208 // claiming/failing them are all separate and don't affect each other
1209 let chanmon_cfgs = create_chanmon_cfgs(6);
1210 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1211 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1212 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1214 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1215 create_announced_chan_between_nodes(&nodes, 0, 3);
1216 create_announced_chan_between_nodes(&nodes, 1, 3);
1217 create_announced_chan_between_nodes(&nodes, 2, 3);
1218 create_announced_chan_between_nodes(&nodes, 3, 4);
1219 create_announced_chan_between_nodes(&nodes, 3, 5);
1221 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1223 *nodes[0].network_payment_count.borrow_mut() -= 1;
1224 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1226 *nodes[0].network_payment_count.borrow_mut() -= 1;
1227 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1229 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1230 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1231 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1235 fn test_duplicate_htlc_different_direction_onchain() {
1236 // Test that ChannelMonitor doesn't generate 2 preimage txn
1237 // when we have 2 HTLCs with same preimage that go across a node
1238 // in opposite directions, even with the same payment secret.
1239 let chanmon_cfgs = create_chanmon_cfgs(2);
1240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1242 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1244 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1247 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1249 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1251 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1252 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1253 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1255 // Provide preimage to node 0 by claiming payment
1256 nodes[0].node.claim_funds(payment_preimage);
1257 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1258 check_added_monitors!(nodes[0], 1);
1260 // Broadcast node 1 commitment txn
1261 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1263 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1264 let mut has_both_htlcs = 0; // check htlcs match ones committed
1265 for outp in remote_txn[0].output.iter() {
1266 if outp.value == 800_000 / 1000 {
1267 has_both_htlcs += 1;
1268 } else if outp.value == 900_000 / 1000 {
1269 has_both_htlcs += 1;
1272 assert_eq!(has_both_htlcs, 2);
1274 mine_transaction(&nodes[0], &remote_txn[0]);
1275 check_added_monitors!(nodes[0], 1);
1276 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1277 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1279 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1280 assert_eq!(claim_txn.len(), 3);
1282 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1283 check_spends!(claim_txn[1], remote_txn[0]);
1284 check_spends!(claim_txn[2], remote_txn[0]);
1285 let preimage_tx = &claim_txn[0];
1286 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1287 (&claim_txn[1], &claim_txn[2])
1289 (&claim_txn[2], &claim_txn[1])
1292 assert_eq!(preimage_tx.input.len(), 1);
1293 assert_eq!(preimage_bump_tx.input.len(), 1);
1295 assert_eq!(preimage_tx.input.len(), 1);
1296 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1297 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1299 assert_eq!(timeout_tx.input.len(), 1);
1300 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1301 check_spends!(timeout_tx, remote_txn[0]);
1302 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1304 let events = nodes[0].node.get_and_clear_pending_msg_events();
1305 assert_eq!(events.len(), 3);
1308 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1309 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1310 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1311 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1313 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, .. } } => {
1314 assert!(update_add_htlcs.is_empty());
1315 assert!(update_fail_htlcs.is_empty());
1316 assert_eq!(update_fulfill_htlcs.len(), 1);
1317 assert!(update_fail_malformed_htlcs.is_empty());
1318 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1320 _ => panic!("Unexpected event"),
1326 fn test_basic_channel_reserve() {
1327 let chanmon_cfgs = create_chanmon_cfgs(2);
1328 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1329 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1330 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1331 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1333 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1334 let channel_reserve = chan_stat.channel_reserve_msat;
1336 // The 2* and +1 are for the fee spike reserve.
1337 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));
1338 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1339 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1340 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1342 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1344 &APIError::ChannelUnavailable{ref err} =>
1345 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1346 _ => panic!("Unexpected error variant"),
1349 _ => panic!("Unexpected error variant"),
1351 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1352 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1354 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1358 fn test_fee_spike_violation_fails_htlc() {
1359 let chanmon_cfgs = create_chanmon_cfgs(2);
1360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1363 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1365 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1366 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1367 let secp_ctx = Secp256k1::new();
1368 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1370 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1372 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1373 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1374 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1375 let msg = msgs::UpdateAddHTLC {
1378 amount_msat: htlc_msat,
1379 payment_hash: payment_hash,
1380 cltv_expiry: htlc_cltv,
1381 onion_routing_packet: onion_packet,
1384 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1386 // Now manually create the commitment_signed message corresponding to the update_add
1387 // nodes[0] just sent. In the code for construction of this message, "local" refers
1388 // to the sender of the message, and "remote" refers to the receiver.
1390 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1392 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1394 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1395 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1396 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1397 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1398 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1399 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1400 let chan_signer = local_chan.get_signer();
1401 // Make the signer believe we validated another commitment, so we can release the secret
1402 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1404 let pubkeys = chan_signer.pubkeys();
1405 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1406 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1407 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1408 chan_signer.pubkeys().funding_pubkey)
1410 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1411 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1412 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1413 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1414 let chan_signer = remote_chan.get_signer();
1415 let pubkeys = chan_signer.pubkeys();
1416 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1417 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1418 chan_signer.pubkeys().funding_pubkey)
1421 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1422 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1423 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1425 // Build the remote commitment transaction so we can sign it, and then later use the
1426 // signature for the commitment_signed message.
1427 let local_chan_balance = 1313;
1429 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1431 amount_msat: 3460001,
1432 cltv_expiry: htlc_cltv,
1434 transaction_output_index: Some(1),
1437 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1440 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1441 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1442 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1443 let local_chan_signer = local_chan.get_signer();
1444 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1448 local_chan.opt_anchors(), local_funding, remote_funding,
1449 commit_tx_keys.clone(),
1451 &mut vec![(accepted_htlc_info, ())],
1452 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1454 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1457 let commit_signed_msg = msgs::CommitmentSigned {
1460 htlc_signatures: res.1,
1462 partial_signature_with_nonce: None,
1465 // Send the commitment_signed message to the nodes[1].
1466 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1467 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1469 // Send the RAA to nodes[1].
1470 let raa_msg = msgs::RevokeAndACK {
1472 per_commitment_secret: local_secret,
1473 next_per_commitment_point: next_local_point,
1475 next_local_nonce: None,
1477 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1479 let events = nodes[1].node.get_and_clear_pending_msg_events();
1480 assert_eq!(events.len(), 1);
1481 // Make sure the HTLC failed in the way we expect.
1483 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1484 assert_eq!(update_fail_htlcs.len(), 1);
1485 update_fail_htlcs[0].clone()
1487 _ => panic!("Unexpected event"),
1489 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1490 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1492 check_added_monitors!(nodes[1], 2);
1496 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1497 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1498 // Set the fee rate for the channel very high, to the point where the fundee
1499 // sending any above-dust amount would result in a channel reserve violation.
1500 // In this test we check that we would be prevented from sending an HTLC in
1502 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1505 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1506 let default_config = UserConfig::default();
1507 let opt_anchors = false;
1509 let mut push_amt = 100_000_000;
1510 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1512 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1514 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1516 // Sending exactly enough to hit the reserve amount should be accepted
1517 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1518 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1521 // However one more HTLC should be significantly over the reserve amount and fail.
1522 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1523 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 },
1524 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1525 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1526 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);
1530 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1531 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1532 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1535 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1536 let default_config = UserConfig::default();
1537 let opt_anchors = false;
1539 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1540 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1541 // transaction fee with 0 HTLCs (183 sats)).
1542 let mut push_amt = 100_000_000;
1543 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1544 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1545 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1547 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1548 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1549 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1552 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1553 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1554 let secp_ctx = Secp256k1::new();
1555 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1556 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1557 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1558 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1559 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1560 let msg = msgs::UpdateAddHTLC {
1562 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1563 amount_msat: htlc_msat,
1564 payment_hash: payment_hash,
1565 cltv_expiry: htlc_cltv,
1566 onion_routing_packet: onion_packet,
1569 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1570 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1571 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);
1572 assert_eq!(nodes[0].node.list_channels().len(), 0);
1573 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1574 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1575 check_added_monitors!(nodes[0], 1);
1576 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() });
1580 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1581 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1582 // calculating our commitment transaction fee (this was previously broken).
1583 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1584 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1586 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1587 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1588 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1589 let default_config = UserConfig::default();
1590 let opt_anchors = false;
1592 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1593 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1594 // transaction fee with 0 HTLCs (183 sats)).
1595 let mut push_amt = 100_000_000;
1596 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1597 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1598 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1600 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1601 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1602 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1603 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1604 // commitment transaction fee.
1605 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1607 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1608 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1609 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1612 // One more than the dust amt should fail, however.
1613 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1614 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 },
1615 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1619 fn test_chan_init_feerate_unaffordability() {
1620 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1621 // channel reserve and feerate requirements.
1622 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1623 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1626 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1627 let default_config = UserConfig::default();
1628 let opt_anchors = false;
1630 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1632 let mut push_amt = 100_000_000;
1633 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1634 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1635 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1637 // During open, we don't have a "counterparty channel reserve" to check against, so that
1638 // requirement only comes into play on the open_channel handling side.
1639 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1640 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1641 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1642 open_channel_msg.push_msat += 1;
1643 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1645 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1646 assert_eq!(msg_events.len(), 1);
1647 match msg_events[0] {
1648 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1649 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1651 _ => panic!("Unexpected event"),
1656 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1657 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1658 // calculating our counterparty's commitment transaction fee (this was previously broken).
1659 let chanmon_cfgs = create_chanmon_cfgs(2);
1660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1662 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1663 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1665 let payment_amt = 46000; // Dust amount
1666 // In the previous code, these first four payments would succeed.
1667 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1668 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1669 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1670 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1672 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1673 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1674 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1675 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1676 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1677 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1680 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1681 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1687 let chanmon_cfgs = create_chanmon_cfgs(3);
1688 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1689 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1690 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1691 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1692 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1695 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1696 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1697 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1698 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1700 // Add a 2* and +1 for the fee spike reserve.
1701 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1702 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;
1703 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1705 // Add a pending HTLC.
1706 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1707 let payment_event_1 = {
1708 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1709 check_added_monitors!(nodes[0], 1);
1711 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1712 assert_eq!(events.len(), 1);
1713 SendEvent::from_event(events.remove(0))
1715 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1717 // Attempt to trigger a channel reserve violation --> payment failure.
1718 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1719 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;
1720 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1721 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1723 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1724 let secp_ctx = Secp256k1::new();
1725 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1726 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1727 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1728 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1729 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1730 let msg = msgs::UpdateAddHTLC {
1733 amount_msat: htlc_msat + 1,
1734 payment_hash: our_payment_hash_1,
1735 cltv_expiry: htlc_cltv,
1736 onion_routing_packet: onion_packet,
1739 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1740 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1741 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1742 assert_eq!(nodes[1].node.list_channels().len(), 1);
1743 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1744 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1745 check_added_monitors!(nodes[1], 1);
1746 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1750 fn test_inbound_outbound_capacity_is_not_zero() {
1751 let chanmon_cfgs = create_chanmon_cfgs(2);
1752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1755 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1756 let channels0 = node_chanmgrs[0].list_channels();
1757 let channels1 = node_chanmgrs[1].list_channels();
1758 let default_config = UserConfig::default();
1759 assert_eq!(channels0.len(), 1);
1760 assert_eq!(channels1.len(), 1);
1762 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1763 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1764 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1766 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1767 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1770 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1771 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1775 fn test_channel_reserve_holding_cell_htlcs() {
1776 let chanmon_cfgs = create_chanmon_cfgs(3);
1777 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1778 // When this test was written, the default base fee floated based on the HTLC count.
1779 // It is now fixed, so we simply set the fee to the expected value here.
1780 let mut config = test_default_channel_config();
1781 config.channel_config.forwarding_fee_base_msat = 239;
1782 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1783 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1784 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1785 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1787 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1788 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1790 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1791 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1793 macro_rules! expect_forward {
1795 let mut events = $node.node.get_and_clear_pending_msg_events();
1796 assert_eq!(events.len(), 1);
1797 check_added_monitors!($node, 1);
1798 let payment_event = SendEvent::from_event(events.remove(0));
1803 let feemsat = 239; // set above
1804 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1805 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1806 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1808 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1810 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1812 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1813 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1814 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);
1815 route.paths[0].last_mut().unwrap().fee_msat += 1;
1816 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1818 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 },
1819 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)));
1820 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1821 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);
1824 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1825 // nodes[0]'s wealth
1827 let amt_msat = recv_value_0 + total_fee_msat;
1828 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1829 // Also, ensure that each payment has enough to be over the dust limit to
1830 // ensure it'll be included in each commit tx fee calculation.
1831 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1832 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1833 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1837 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1838 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1839 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1840 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1841 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1843 let (stat01_, stat11_, stat12_, stat22_) = (
1844 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1845 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1846 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1847 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1850 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1851 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1852 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1853 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1854 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1857 // adding pending output.
1858 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1859 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1860 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1861 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1862 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1863 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1864 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1865 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1866 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1868 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1869 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1870 let amt_msat_1 = recv_value_1 + total_fee_msat;
1872 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);
1873 let payment_event_1 = {
1874 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1875 check_added_monitors!(nodes[0], 1);
1877 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1878 assert_eq!(events.len(), 1);
1879 SendEvent::from_event(events.remove(0))
1881 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1883 // channel reserve test with htlc pending output > 0
1884 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1886 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1887 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 },
1888 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1889 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1892 // split the rest to test holding cell
1893 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1894 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1895 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1896 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1898 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1899 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);
1902 // now see if they go through on both sides
1903 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);
1904 // but this will stuck in the holding cell
1905 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1906 check_added_monitors!(nodes[0], 0);
1907 let events = nodes[0].node.get_and_clear_pending_events();
1908 assert_eq!(events.len(), 0);
1910 // test with outbound holding cell amount > 0
1912 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1913 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 },
1914 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1915 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1916 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1919 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);
1920 // this will also stuck in the holding cell
1921 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1922 check_added_monitors!(nodes[0], 0);
1923 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1924 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1926 // flush the pending htlc
1927 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1928 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1929 check_added_monitors!(nodes[1], 1);
1931 // the pending htlc should be promoted to committed
1932 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1933 check_added_monitors!(nodes[0], 1);
1934 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1936 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1937 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1938 // No commitment_signed so get_event_msg's assert(len == 1) passes
1939 check_added_monitors!(nodes[0], 1);
1941 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1942 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1943 check_added_monitors!(nodes[1], 1);
1945 expect_pending_htlcs_forwardable!(nodes[1]);
1947 let ref payment_event_11 = expect_forward!(nodes[1]);
1948 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1949 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1951 expect_pending_htlcs_forwardable!(nodes[2]);
1952 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1954 // flush the htlcs in the holding cell
1955 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1956 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1957 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1958 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1959 expect_pending_htlcs_forwardable!(nodes[1]);
1961 let ref payment_event_3 = expect_forward!(nodes[1]);
1962 assert_eq!(payment_event_3.msgs.len(), 2);
1963 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1964 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1966 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1967 expect_pending_htlcs_forwardable!(nodes[2]);
1969 let events = nodes[2].node.get_and_clear_pending_events();
1970 assert_eq!(events.len(), 2);
1972 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1973 assert_eq!(our_payment_hash_21, *payment_hash);
1974 assert_eq!(recv_value_21, amount_msat);
1975 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1976 assert_eq!(via_channel_id, Some(chan_2.2));
1978 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1979 assert!(payment_preimage.is_none());
1980 assert_eq!(our_payment_secret_21, *payment_secret);
1982 _ => panic!("expected PaymentPurpose::InvoicePayment")
1985 _ => panic!("Unexpected event"),
1988 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1989 assert_eq!(our_payment_hash_22, *payment_hash);
1990 assert_eq!(recv_value_22, amount_msat);
1991 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1992 assert_eq!(via_channel_id, Some(chan_2.2));
1994 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1995 assert!(payment_preimage.is_none());
1996 assert_eq!(our_payment_secret_22, *payment_secret);
1998 _ => panic!("expected PaymentPurpose::InvoicePayment")
2001 _ => panic!("Unexpected event"),
2004 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2005 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2006 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2008 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2009 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2010 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2012 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2013 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);
2014 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2015 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2016 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2018 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2019 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2023 fn channel_reserve_in_flight_removes() {
2024 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2025 // can send to its counterparty, but due to update ordering, the other side may not yet have
2026 // considered those HTLCs fully removed.
2027 // This tests that we don't count HTLCs which will not be included in the next remote
2028 // commitment transaction towards the reserve value (as it implies no commitment transaction
2029 // will be generated which violates the remote reserve value).
2030 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2032 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2033 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2034 // you only consider the value of the first HTLC, it may not),
2035 // * start routing a third HTLC from A to B,
2036 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2037 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2038 // * deliver the first fulfill from B
2039 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2041 // * deliver A's response CS and RAA.
2042 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2043 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2044 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2045 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2046 let chanmon_cfgs = create_chanmon_cfgs(2);
2047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2050 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2052 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2053 // Route the first two HTLCs.
2054 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2055 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2056 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2058 // Start routing the third HTLC (this is just used to get everyone in the right state).
2059 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2061 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2062 check_added_monitors!(nodes[0], 1);
2063 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2064 assert_eq!(events.len(), 1);
2065 SendEvent::from_event(events.remove(0))
2068 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2069 // initial fulfill/CS.
2070 nodes[1].node.claim_funds(payment_preimage_1);
2071 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2072 check_added_monitors!(nodes[1], 1);
2073 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2075 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2076 // remove the second HTLC when we send the HTLC back from B to A.
2077 nodes[1].node.claim_funds(payment_preimage_2);
2078 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2079 check_added_monitors!(nodes[1], 1);
2080 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2082 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2083 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2084 check_added_monitors!(nodes[0], 1);
2085 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2086 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2088 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2089 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2090 check_added_monitors!(nodes[1], 1);
2091 // B is already AwaitingRAA, so cant generate a CS here
2092 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2094 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2095 check_added_monitors!(nodes[1], 1);
2096 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2098 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2099 check_added_monitors!(nodes[0], 1);
2100 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2102 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2103 check_added_monitors!(nodes[1], 1);
2104 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2106 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2107 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2108 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2109 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2110 // on-chain as necessary).
2111 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2112 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2113 check_added_monitors!(nodes[0], 1);
2114 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2115 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2117 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2118 check_added_monitors!(nodes[1], 1);
2119 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2121 expect_pending_htlcs_forwardable!(nodes[1]);
2122 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2124 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2125 // resolve the second HTLC from A's point of view.
2126 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2127 check_added_monitors!(nodes[0], 1);
2128 expect_payment_path_successful!(nodes[0]);
2129 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2131 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2132 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2133 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2135 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2136 check_added_monitors!(nodes[1], 1);
2137 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2138 assert_eq!(events.len(), 1);
2139 SendEvent::from_event(events.remove(0))
2142 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2143 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2144 check_added_monitors!(nodes[0], 1);
2145 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2147 // Now just resolve all the outstanding messages/HTLCs for completeness...
2149 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2150 check_added_monitors!(nodes[1], 1);
2151 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2153 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2154 check_added_monitors!(nodes[1], 1);
2156 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2157 check_added_monitors!(nodes[0], 1);
2158 expect_payment_path_successful!(nodes[0]);
2159 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2161 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2162 check_added_monitors!(nodes[1], 1);
2163 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2165 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2166 check_added_monitors!(nodes[0], 1);
2168 expect_pending_htlcs_forwardable!(nodes[0]);
2169 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2171 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2172 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2176 fn channel_monitor_network_test() {
2177 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2178 // tests that ChannelMonitor is able to recover from various states.
2179 let chanmon_cfgs = create_chanmon_cfgs(5);
2180 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2181 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2182 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2184 // Create some initial channels
2185 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2186 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2187 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2188 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2190 // Make sure all nodes are at the same starting height
2191 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2192 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2193 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2194 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2195 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2197 // Rebalance the network a bit by relaying one payment through all the channels...
2198 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2199 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2201 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2203 // Simple case with no pending HTLCs:
2204 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2205 check_added_monitors!(nodes[1], 1);
2206 check_closed_broadcast!(nodes[1], true);
2208 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2209 assert_eq!(node_txn.len(), 1);
2210 mine_transaction(&nodes[0], &node_txn[0]);
2211 check_added_monitors!(nodes[0], 1);
2212 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2214 check_closed_broadcast!(nodes[0], true);
2215 assert_eq!(nodes[0].node.list_channels().len(), 0);
2216 assert_eq!(nodes[1].node.list_channels().len(), 1);
2217 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2218 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2220 // One pending HTLC is discarded by the force-close:
2221 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2223 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2224 // broadcasted until we reach the timelock time).
2225 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2226 check_closed_broadcast!(nodes[1], true);
2227 check_added_monitors!(nodes[1], 1);
2229 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2230 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2231 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2232 mine_transaction(&nodes[2], &node_txn[0]);
2233 check_added_monitors!(nodes[2], 1);
2234 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2236 check_closed_broadcast!(nodes[2], true);
2237 assert_eq!(nodes[1].node.list_channels().len(), 0);
2238 assert_eq!(nodes[2].node.list_channels().len(), 1);
2239 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2240 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2242 macro_rules! claim_funds {
2243 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2245 $node.node.claim_funds($preimage);
2246 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2247 check_added_monitors!($node, 1);
2249 let events = $node.node.get_and_clear_pending_msg_events();
2250 assert_eq!(events.len(), 1);
2252 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2253 assert!(update_add_htlcs.is_empty());
2254 assert!(update_fail_htlcs.is_empty());
2255 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2257 _ => panic!("Unexpected event"),
2263 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2264 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2265 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2266 check_added_monitors!(nodes[2], 1);
2267 check_closed_broadcast!(nodes[2], true);
2268 let node2_commitment_txid;
2270 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2271 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2272 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2273 node2_commitment_txid = node_txn[0].txid();
2275 // Claim the payment on nodes[3], giving it knowledge of the preimage
2276 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2277 mine_transaction(&nodes[3], &node_txn[0]);
2278 check_added_monitors!(nodes[3], 1);
2279 check_preimage_claim(&nodes[3], &node_txn);
2281 check_closed_broadcast!(nodes[3], true);
2282 assert_eq!(nodes[2].node.list_channels().len(), 0);
2283 assert_eq!(nodes[3].node.list_channels().len(), 1);
2284 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2285 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2287 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2288 // confusing us in the following tests.
2289 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2291 // One pending HTLC to time out:
2292 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2293 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2296 let (close_chan_update_1, close_chan_update_2) = {
2297 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2298 let events = nodes[3].node.get_and_clear_pending_msg_events();
2299 assert_eq!(events.len(), 2);
2300 let close_chan_update_1 = match events[0] {
2301 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2304 _ => panic!("Unexpected event"),
2307 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2308 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2310 _ => panic!("Unexpected event"),
2312 check_added_monitors!(nodes[3], 1);
2314 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2316 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2317 node_txn.retain(|tx| {
2318 if tx.input[0].previous_output.txid == node2_commitment_txid {
2324 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2326 // Claim the payment on nodes[4], giving it knowledge of the preimage
2327 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2329 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2330 let events = nodes[4].node.get_and_clear_pending_msg_events();
2331 assert_eq!(events.len(), 2);
2332 let close_chan_update_2 = match events[0] {
2333 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2336 _ => panic!("Unexpected event"),
2339 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2340 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2342 _ => panic!("Unexpected event"),
2344 check_added_monitors!(nodes[4], 1);
2345 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2347 mine_transaction(&nodes[4], &node_txn[0]);
2348 check_preimage_claim(&nodes[4], &node_txn);
2349 (close_chan_update_1, close_chan_update_2)
2351 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2352 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2353 assert_eq!(nodes[3].node.list_channels().len(), 0);
2354 assert_eq!(nodes[4].node.list_channels().len(), 0);
2356 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2357 ChannelMonitorUpdateStatus::Completed);
2358 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2359 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2363 fn test_justice_tx() {
2364 // Test justice txn built on revoked HTLC-Success tx, against both sides
2365 let mut alice_config = UserConfig::default();
2366 alice_config.channel_handshake_config.announced_channel = true;
2367 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2368 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2369 let mut bob_config = UserConfig::default();
2370 bob_config.channel_handshake_config.announced_channel = true;
2371 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2372 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2373 let user_cfgs = [Some(alice_config), Some(bob_config)];
2374 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2375 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2376 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2377 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2378 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2379 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2380 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2381 // Create some new channels:
2382 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2384 // A pending HTLC which will be revoked:
2385 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2386 // Get the will-be-revoked local txn from nodes[0]
2387 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2388 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2389 assert_eq!(revoked_local_txn[0].input.len(), 1);
2390 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2391 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2392 assert_eq!(revoked_local_txn[1].input.len(), 1);
2393 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2394 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2395 // Revoke the old state
2396 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2399 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2401 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2402 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2403 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2405 check_spends!(node_txn[0], revoked_local_txn[0]);
2406 node_txn.swap_remove(0);
2408 check_added_monitors!(nodes[1], 1);
2409 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2410 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2412 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2413 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2414 // Verify broadcast of revoked HTLC-timeout
2415 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2416 check_added_monitors!(nodes[0], 1);
2417 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2418 // Broadcast revoked HTLC-timeout on node 1
2419 mine_transaction(&nodes[1], &node_txn[1]);
2420 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2422 get_announce_close_broadcast_events(&nodes, 0, 1);
2424 assert_eq!(nodes[0].node.list_channels().len(), 0);
2425 assert_eq!(nodes[1].node.list_channels().len(), 0);
2427 // We test justice_tx build by A on B's revoked HTLC-Success tx
2428 // Create some new channels:
2429 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2431 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2435 // A pending HTLC which will be revoked:
2436 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2437 // Get the will-be-revoked local txn from B
2438 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2439 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2440 assert_eq!(revoked_local_txn[0].input.len(), 1);
2441 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2442 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2443 // Revoke the old state
2444 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2446 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2448 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2449 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2450 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2452 check_spends!(node_txn[0], revoked_local_txn[0]);
2453 node_txn.swap_remove(0);
2455 check_added_monitors!(nodes[0], 1);
2456 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2458 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2459 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2460 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2461 check_added_monitors!(nodes[1], 1);
2462 mine_transaction(&nodes[0], &node_txn[1]);
2463 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2464 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2466 get_announce_close_broadcast_events(&nodes, 0, 1);
2467 assert_eq!(nodes[0].node.list_channels().len(), 0);
2468 assert_eq!(nodes[1].node.list_channels().len(), 0);
2472 fn revoked_output_claim() {
2473 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2474 // transaction is broadcast by its counterparty
2475 let chanmon_cfgs = create_chanmon_cfgs(2);
2476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2478 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2479 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2480 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2481 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2482 assert_eq!(revoked_local_txn.len(), 1);
2483 // Only output is the full channel value back to nodes[0]:
2484 assert_eq!(revoked_local_txn[0].output.len(), 1);
2485 // Send a payment through, updating everyone's latest commitment txn
2486 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2488 // Inform nodes[1] that nodes[0] broadcast a stale tx
2489 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2490 check_added_monitors!(nodes[1], 1);
2491 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2492 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2493 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2495 check_spends!(node_txn[0], revoked_local_txn[0]);
2497 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2498 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2499 get_announce_close_broadcast_events(&nodes, 0, 1);
2500 check_added_monitors!(nodes[0], 1);
2501 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2505 fn claim_htlc_outputs_shared_tx() {
2506 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2507 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2508 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2511 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2513 // Create some new channel:
2514 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2516 // Rebalance the network to generate htlc in the two directions
2517 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2518 // 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
2519 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2520 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2522 // Get the will-be-revoked local txn from node[0]
2523 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2524 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2525 assert_eq!(revoked_local_txn[0].input.len(), 1);
2526 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2527 assert_eq!(revoked_local_txn[1].input.len(), 1);
2528 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2529 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2530 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2532 //Revoke the old state
2533 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2536 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2537 check_added_monitors!(nodes[0], 1);
2538 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2539 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2540 check_added_monitors!(nodes[1], 1);
2541 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2542 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2543 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2545 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2546 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2548 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2549 check_spends!(node_txn[0], revoked_local_txn[0]);
2551 let mut witness_lens = BTreeSet::new();
2552 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2553 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2554 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2555 assert_eq!(witness_lens.len(), 3);
2556 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2557 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2558 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2560 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2561 // ANTI_REORG_DELAY confirmations.
2562 mine_transaction(&nodes[1], &node_txn[0]);
2563 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2564 expect_payment_failed!(nodes[1], payment_hash_2, false);
2566 get_announce_close_broadcast_events(&nodes, 0, 1);
2567 assert_eq!(nodes[0].node.list_channels().len(), 0);
2568 assert_eq!(nodes[1].node.list_channels().len(), 0);
2572 fn claim_htlc_outputs_single_tx() {
2573 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2574 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2575 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2576 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2577 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2578 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2580 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2582 // Rebalance the network to generate htlc in the two directions
2583 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2584 // 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
2585 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2586 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2587 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2589 // Get the will-be-revoked local txn from node[0]
2590 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2592 //Revoke the old state
2593 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2596 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2597 check_added_monitors!(nodes[0], 1);
2598 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2599 check_added_monitors!(nodes[1], 1);
2600 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2601 let mut events = nodes[0].node.get_and_clear_pending_events();
2602 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2603 match events.last().unwrap() {
2604 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2605 _ => panic!("Unexpected event"),
2608 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2609 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2611 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2612 assert_eq!(node_txn.len(), 7);
2614 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2615 assert_eq!(node_txn[0].input.len(), 1);
2616 check_spends!(node_txn[0], chan_1.3);
2617 assert_eq!(node_txn[1].input.len(), 1);
2618 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2619 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2620 check_spends!(node_txn[1], node_txn[0]);
2622 // Justice transactions are indices 2-3-4
2623 assert_eq!(node_txn[2].input.len(), 1);
2624 assert_eq!(node_txn[3].input.len(), 1);
2625 assert_eq!(node_txn[4].input.len(), 1);
2627 check_spends!(node_txn[2], revoked_local_txn[0]);
2628 check_spends!(node_txn[3], revoked_local_txn[0]);
2629 check_spends!(node_txn[4], revoked_local_txn[0]);
2631 let mut witness_lens = BTreeSet::new();
2632 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2633 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2634 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2635 assert_eq!(witness_lens.len(), 3);
2636 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2637 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2638 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2640 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2641 // ANTI_REORG_DELAY confirmations.
2642 mine_transaction(&nodes[1], &node_txn[2]);
2643 mine_transaction(&nodes[1], &node_txn[3]);
2644 mine_transaction(&nodes[1], &node_txn[4]);
2645 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2646 expect_payment_failed!(nodes[1], payment_hash_2, false);
2648 get_announce_close_broadcast_events(&nodes, 0, 1);
2649 assert_eq!(nodes[0].node.list_channels().len(), 0);
2650 assert_eq!(nodes[1].node.list_channels().len(), 0);
2654 fn test_htlc_on_chain_success() {
2655 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2656 // the preimage backward accordingly. So here we test that ChannelManager is
2657 // broadcasting the right event to other nodes in payment path.
2658 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2659 // A --------------------> B ----------------------> C (preimage)
2660 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2661 // commitment transaction was broadcast.
2662 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2664 // B should be able to claim via preimage if A then broadcasts its local tx.
2665 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2666 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2667 // PaymentSent event).
2669 let chanmon_cfgs = create_chanmon_cfgs(3);
2670 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2671 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2672 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2674 // Create some initial channels
2675 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2676 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2678 // Ensure all nodes are at the same height
2679 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2680 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2681 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2682 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2684 // Rebalance the network a bit by relaying one payment through all the channels...
2685 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2686 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2688 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2689 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2691 // Broadcast legit commitment tx from C on B's chain
2692 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2693 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2694 assert_eq!(commitment_tx.len(), 1);
2695 check_spends!(commitment_tx[0], chan_2.3);
2696 nodes[2].node.claim_funds(our_payment_preimage);
2697 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2698 nodes[2].node.claim_funds(our_payment_preimage_2);
2699 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2700 check_added_monitors!(nodes[2], 2);
2701 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2702 assert!(updates.update_add_htlcs.is_empty());
2703 assert!(updates.update_fail_htlcs.is_empty());
2704 assert!(updates.update_fail_malformed_htlcs.is_empty());
2705 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2707 mine_transaction(&nodes[2], &commitment_tx[0]);
2708 check_closed_broadcast!(nodes[2], true);
2709 check_added_monitors!(nodes[2], 1);
2710 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2711 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2712 assert_eq!(node_txn.len(), 2);
2713 check_spends!(node_txn[0], commitment_tx[0]);
2714 check_spends!(node_txn[1], commitment_tx[0]);
2715 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2716 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2717 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2718 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2719 assert_eq!(node_txn[0].lock_time.0, 0);
2720 assert_eq!(node_txn[1].lock_time.0, 0);
2722 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2723 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2724 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2725 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2727 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2728 assert_eq!(added_monitors.len(), 1);
2729 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2730 added_monitors.clear();
2732 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2733 assert_eq!(forwarded_events.len(), 3);
2734 match forwarded_events[0] {
2735 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2736 _ => panic!("Unexpected event"),
2738 let chan_id = Some(chan_1.2);
2739 match forwarded_events[1] {
2740 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2741 assert_eq!(fee_earned_msat, Some(1000));
2742 assert_eq!(prev_channel_id, chan_id);
2743 assert_eq!(claim_from_onchain_tx, true);
2744 assert_eq!(next_channel_id, Some(chan_2.2));
2745 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2749 match forwarded_events[2] {
2750 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2751 assert_eq!(fee_earned_msat, Some(1000));
2752 assert_eq!(prev_channel_id, chan_id);
2753 assert_eq!(claim_from_onchain_tx, true);
2754 assert_eq!(next_channel_id, Some(chan_2.2));
2755 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2759 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2761 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2762 assert_eq!(added_monitors.len(), 2);
2763 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2764 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2765 added_monitors.clear();
2767 assert_eq!(events.len(), 3);
2769 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2770 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2772 match nodes_2_event {
2773 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2774 _ => panic!("Unexpected event"),
2777 match nodes_0_event {
2778 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, .. } } => {
2779 assert!(update_add_htlcs.is_empty());
2780 assert!(update_fail_htlcs.is_empty());
2781 assert_eq!(update_fulfill_htlcs.len(), 1);
2782 assert!(update_fail_malformed_htlcs.is_empty());
2783 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2785 _ => panic!("Unexpected event"),
2788 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2790 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2791 _ => panic!("Unexpected event"),
2794 macro_rules! check_tx_local_broadcast {
2795 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2796 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2797 assert_eq!(node_txn.len(), 2);
2798 // Node[1]: 2 * HTLC-timeout tx
2799 // Node[0]: 2 * HTLC-timeout tx
2800 check_spends!(node_txn[0], $commitment_tx);
2801 check_spends!(node_txn[1], $commitment_tx);
2802 assert_ne!(node_txn[0].lock_time.0, 0);
2803 assert_ne!(node_txn[1].lock_time.0, 0);
2805 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2806 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2807 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2808 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2810 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2811 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2812 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2813 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2818 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2819 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2821 // Broadcast legit commitment tx from A on B's chain
2822 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2823 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2824 check_spends!(node_a_commitment_tx[0], chan_1.3);
2825 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2826 check_closed_broadcast!(nodes[1], true);
2827 check_added_monitors!(nodes[1], 1);
2828 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2829 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2830 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2831 let commitment_spend =
2832 if node_txn.len() == 1 {
2835 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2836 // FullBlockViaListen
2837 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2838 check_spends!(node_txn[1], commitment_tx[0]);
2839 check_spends!(node_txn[2], commitment_tx[0]);
2840 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2843 check_spends!(node_txn[0], commitment_tx[0]);
2844 check_spends!(node_txn[1], commitment_tx[0]);
2845 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2850 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2851 assert_eq!(commitment_spend.input.len(), 2);
2852 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2853 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2854 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2855 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2857 // we already checked the same situation with A.
2859 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2860 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2861 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2862 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2863 check_closed_broadcast!(nodes[0], true);
2864 check_added_monitors!(nodes[0], 1);
2865 let events = nodes[0].node.get_and_clear_pending_events();
2866 assert_eq!(events.len(), 5);
2867 let mut first_claimed = false;
2868 for event in events {
2870 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2871 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2872 assert!(!first_claimed);
2873 first_claimed = true;
2875 assert_eq!(payment_preimage, our_payment_preimage_2);
2876 assert_eq!(payment_hash, payment_hash_2);
2879 Event::PaymentPathSuccessful { .. } => {},
2880 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2881 _ => panic!("Unexpected event"),
2884 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2887 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2888 // Test that in case of a unilateral close onchain, we detect the state of output and
2889 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2890 // broadcasting the right event to other nodes in payment path.
2891 // A ------------------> B ----------------------> C (timeout)
2892 // B's commitment tx C's commitment tx
2894 // B's HTLC timeout tx B's timeout tx
2896 let chanmon_cfgs = create_chanmon_cfgs(3);
2897 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2898 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2899 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2900 *nodes[0].connect_style.borrow_mut() = connect_style;
2901 *nodes[1].connect_style.borrow_mut() = connect_style;
2902 *nodes[2].connect_style.borrow_mut() = connect_style;
2904 // Create some intial channels
2905 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2906 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2908 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2909 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2910 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2912 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2914 // Broadcast legit commitment tx from C on B's chain
2915 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2916 check_spends!(commitment_tx[0], chan_2.3);
2917 nodes[2].node.fail_htlc_backwards(&payment_hash);
2918 check_added_monitors!(nodes[2], 0);
2919 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2920 check_added_monitors!(nodes[2], 1);
2922 let events = nodes[2].node.get_and_clear_pending_msg_events();
2923 assert_eq!(events.len(), 1);
2925 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, .. } } => {
2926 assert!(update_add_htlcs.is_empty());
2927 assert!(!update_fail_htlcs.is_empty());
2928 assert!(update_fulfill_htlcs.is_empty());
2929 assert!(update_fail_malformed_htlcs.is_empty());
2930 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2932 _ => panic!("Unexpected event"),
2934 mine_transaction(&nodes[2], &commitment_tx[0]);
2935 check_closed_broadcast!(nodes[2], true);
2936 check_added_monitors!(nodes[2], 1);
2937 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2938 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2939 assert_eq!(node_txn.len(), 0);
2941 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2942 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2943 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2944 mine_transaction(&nodes[1], &commitment_tx[0]);
2945 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2948 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2949 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2951 check_spends!(node_txn[2], commitment_tx[0]);
2952 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2954 check_spends!(node_txn[0], chan_2.3);
2955 check_spends!(node_txn[1], node_txn[0]);
2956 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2957 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2959 timeout_tx = node_txn[2].clone();
2963 mine_transaction(&nodes[1], &timeout_tx);
2964 check_added_monitors!(nodes[1], 1);
2965 check_closed_broadcast!(nodes[1], true);
2967 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2969 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 }]);
2970 check_added_monitors!(nodes[1], 1);
2971 let events = nodes[1].node.get_and_clear_pending_msg_events();
2972 assert_eq!(events.len(), 1);
2974 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, .. } } => {
2975 assert!(update_add_htlcs.is_empty());
2976 assert!(!update_fail_htlcs.is_empty());
2977 assert!(update_fulfill_htlcs.is_empty());
2978 assert!(update_fail_malformed_htlcs.is_empty());
2979 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2981 _ => panic!("Unexpected event"),
2984 // Broadcast legit commitment tx from B on A's chain
2985 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2986 check_spends!(commitment_tx[0], chan_1.3);
2988 mine_transaction(&nodes[0], &commitment_tx[0]);
2989 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2991 check_closed_broadcast!(nodes[0], true);
2992 check_added_monitors!(nodes[0], 1);
2993 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2994 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2995 assert_eq!(node_txn.len(), 1);
2996 check_spends!(node_txn[0], commitment_tx[0]);
2997 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3001 fn test_htlc_on_chain_timeout() {
3002 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3003 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3004 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3008 fn test_simple_commitment_revoked_fail_backward() {
3009 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3010 // and fail backward accordingly.
3012 let chanmon_cfgs = create_chanmon_cfgs(3);
3013 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3014 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3015 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3017 // Create some initial channels
3018 create_announced_chan_between_nodes(&nodes, 0, 1);
3019 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3021 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3022 // Get the will-be-revoked local txn from nodes[2]
3023 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3024 // Revoke the old state
3025 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3027 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3029 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3030 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3031 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3032 check_added_monitors!(nodes[1], 1);
3033 check_closed_broadcast!(nodes[1], true);
3035 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 }]);
3036 check_added_monitors!(nodes[1], 1);
3037 let events = nodes[1].node.get_and_clear_pending_msg_events();
3038 assert_eq!(events.len(), 1);
3040 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, .. } } => {
3041 assert!(update_add_htlcs.is_empty());
3042 assert_eq!(update_fail_htlcs.len(), 1);
3043 assert!(update_fulfill_htlcs.is_empty());
3044 assert!(update_fail_malformed_htlcs.is_empty());
3045 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3047 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3048 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3049 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3051 _ => panic!("Unexpected event"),
3055 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3056 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3057 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3058 // commitment transaction anymore.
3059 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3060 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3061 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3062 // technically disallowed and we should probably handle it reasonably.
3063 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3064 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3066 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3067 // commitment_signed (implying it will be in the latest remote commitment transaction).
3068 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3069 // and once they revoke the previous commitment transaction (allowing us to send a new
3070 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3071 let chanmon_cfgs = create_chanmon_cfgs(3);
3072 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3073 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3074 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3076 // Create some initial channels
3077 create_announced_chan_between_nodes(&nodes, 0, 1);
3078 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3080 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 });
3081 // Get the will-be-revoked local txn from nodes[2]
3082 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3083 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3084 // Revoke the old state
3085 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3087 let value = if use_dust {
3088 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3089 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3090 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3091 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3094 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3095 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3096 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3098 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3099 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3100 check_added_monitors!(nodes[2], 1);
3101 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3102 assert!(updates.update_add_htlcs.is_empty());
3103 assert!(updates.update_fulfill_htlcs.is_empty());
3104 assert!(updates.update_fail_malformed_htlcs.is_empty());
3105 assert_eq!(updates.update_fail_htlcs.len(), 1);
3106 assert!(updates.update_fee.is_none());
3107 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3108 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3109 // Drop the last RAA from 3 -> 2
3111 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3112 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3113 check_added_monitors!(nodes[2], 1);
3114 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3115 assert!(updates.update_add_htlcs.is_empty());
3116 assert!(updates.update_fulfill_htlcs.is_empty());
3117 assert!(updates.update_fail_malformed_htlcs.is_empty());
3118 assert_eq!(updates.update_fail_htlcs.len(), 1);
3119 assert!(updates.update_fee.is_none());
3120 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3121 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3122 check_added_monitors!(nodes[1], 1);
3123 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3124 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3125 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3126 check_added_monitors!(nodes[2], 1);
3128 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3129 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3130 check_added_monitors!(nodes[2], 1);
3131 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132 assert!(updates.update_add_htlcs.is_empty());
3133 assert!(updates.update_fulfill_htlcs.is_empty());
3134 assert!(updates.update_fail_malformed_htlcs.is_empty());
3135 assert_eq!(updates.update_fail_htlcs.len(), 1);
3136 assert!(updates.update_fee.is_none());
3137 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138 // At this point first_payment_hash has dropped out of the latest two commitment
3139 // transactions that nodes[1] is tracking...
3140 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3141 check_added_monitors!(nodes[1], 1);
3142 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3143 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3144 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3145 check_added_monitors!(nodes[2], 1);
3147 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3148 // on nodes[2]'s RAA.
3149 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3150 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3151 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3152 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3153 check_added_monitors!(nodes[1], 0);
3156 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3157 // One monitor for the new revocation preimage, no second on as we won't generate a new
3158 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3159 check_added_monitors!(nodes[1], 1);
3160 let events = nodes[1].node.get_and_clear_pending_events();
3161 assert_eq!(events.len(), 2);
3163 Event::PendingHTLCsForwardable { .. } => { },
3164 _ => panic!("Unexpected event"),
3167 Event::HTLCHandlingFailed { .. } => { },
3168 _ => panic!("Unexpected event"),
3170 // Deliberately don't process the pending fail-back so they all fail back at once after
3171 // block connection just like the !deliver_bs_raa case
3174 let mut failed_htlcs = HashSet::new();
3175 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3177 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3178 check_added_monitors!(nodes[1], 1);
3179 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3181 let events = nodes[1].node.get_and_clear_pending_events();
3182 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3184 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3185 _ => panic!("Unexepected event"),
3188 Event::PaymentPathFailed { ref payment_hash, .. } => {
3189 assert_eq!(*payment_hash, fourth_payment_hash);
3191 _ => panic!("Unexpected event"),
3194 Event::PaymentFailed { ref payment_hash, .. } => {
3195 assert_eq!(*payment_hash, fourth_payment_hash);
3197 _ => panic!("Unexpected event"),
3200 nodes[1].node.process_pending_htlc_forwards();
3201 check_added_monitors!(nodes[1], 1);
3203 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3204 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3207 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3208 match nodes_2_event {
3209 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, .. } } => {
3210 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3211 assert_eq!(update_add_htlcs.len(), 1);
3212 assert!(update_fulfill_htlcs.is_empty());
3213 assert!(update_fail_htlcs.is_empty());
3214 assert!(update_fail_malformed_htlcs.is_empty());
3216 _ => panic!("Unexpected event"),
3220 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3221 match nodes_2_event {
3222 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3223 assert_eq!(channel_id, chan_2.2);
3224 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3226 _ => panic!("Unexpected event"),
3229 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3230 match nodes_0_event {
3231 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, .. } } => {
3232 assert!(update_add_htlcs.is_empty());
3233 assert_eq!(update_fail_htlcs.len(), 3);
3234 assert!(update_fulfill_htlcs.is_empty());
3235 assert!(update_fail_malformed_htlcs.is_empty());
3236 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3238 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3239 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3240 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3242 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3244 let events = nodes[0].node.get_and_clear_pending_events();
3245 assert_eq!(events.len(), 6);
3247 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3248 assert!(failed_htlcs.insert(payment_hash.0));
3249 // If we delivered B's RAA we got an unknown preimage error, not something
3250 // that we should update our routing table for.
3251 if !deliver_bs_raa {
3252 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3255 _ => panic!("Unexpected event"),
3258 Event::PaymentFailed { ref payment_hash, .. } => {
3259 assert_eq!(*payment_hash, first_payment_hash);
3261 _ => panic!("Unexpected event"),
3264 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3265 assert!(failed_htlcs.insert(payment_hash.0));
3267 _ => panic!("Unexpected event"),
3270 Event::PaymentFailed { ref payment_hash, .. } => {
3271 assert_eq!(*payment_hash, second_payment_hash);
3273 _ => panic!("Unexpected event"),
3276 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3277 assert!(failed_htlcs.insert(payment_hash.0));
3279 _ => panic!("Unexpected event"),
3282 Event::PaymentFailed { ref payment_hash, .. } => {
3283 assert_eq!(*payment_hash, third_payment_hash);
3285 _ => panic!("Unexpected event"),
3288 _ => panic!("Unexpected event"),
3291 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3293 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3294 _ => panic!("Unexpected event"),
3297 assert!(failed_htlcs.contains(&first_payment_hash.0));
3298 assert!(failed_htlcs.contains(&second_payment_hash.0));
3299 assert!(failed_htlcs.contains(&third_payment_hash.0));
3303 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3304 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3305 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3306 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3307 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3311 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3312 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3313 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3314 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3315 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3319 fn fail_backward_pending_htlc_upon_channel_failure() {
3320 let chanmon_cfgs = create_chanmon_cfgs(2);
3321 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3322 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3323 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3324 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3326 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3328 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3329 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3330 check_added_monitors!(nodes[0], 1);
3332 let payment_event = {
3333 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3334 assert_eq!(events.len(), 1);
3335 SendEvent::from_event(events.remove(0))
3337 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3338 assert_eq!(payment_event.msgs.len(), 1);
3341 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3342 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3344 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3345 check_added_monitors!(nodes[0], 0);
3347 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3350 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3352 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3354 let secp_ctx = Secp256k1::new();
3355 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3356 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3357 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3358 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3359 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3361 // Send a 0-msat update_add_htlc to fail the channel.
3362 let update_add_htlc = msgs::UpdateAddHTLC {
3368 onion_routing_packet,
3370 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3372 let events = nodes[0].node.get_and_clear_pending_events();
3373 assert_eq!(events.len(), 3);
3374 // Check that Alice fails backward the pending HTLC from the second payment.
3376 Event::PaymentPathFailed { payment_hash, .. } => {
3377 assert_eq!(payment_hash, failed_payment_hash);
3379 _ => panic!("Unexpected event"),
3382 Event::PaymentFailed { payment_hash, .. } => {
3383 assert_eq!(payment_hash, failed_payment_hash);
3385 _ => panic!("Unexpected event"),
3388 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3389 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3391 _ => panic!("Unexpected event {:?}", events[1]),
3393 check_closed_broadcast!(nodes[0], true);
3394 check_added_monitors!(nodes[0], 1);
3398 fn test_htlc_ignore_latest_remote_commitment() {
3399 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3400 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3401 let chanmon_cfgs = create_chanmon_cfgs(2);
3402 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3403 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3404 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3405 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3406 // We rely on the ability to connect a block redundantly, which isn't allowed via
3407 // `chain::Listen`, so we never run the test if we randomly get assigned that
3411 create_announced_chan_between_nodes(&nodes, 0, 1);
3413 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3414 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3415 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3416 check_closed_broadcast!(nodes[0], true);
3417 check_added_monitors!(nodes[0], 1);
3418 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3420 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3421 assert_eq!(node_txn.len(), 3);
3422 assert_eq!(node_txn[0], node_txn[1]);
3424 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3425 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3426 check_closed_broadcast!(nodes[1], true);
3427 check_added_monitors!(nodes[1], 1);
3428 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3430 // Duplicate the connect_block call since this may happen due to other listeners
3431 // registering new transactions
3432 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3436 fn test_force_close_fail_back() {
3437 // Check which HTLCs are failed-backwards on channel force-closure
3438 let chanmon_cfgs = create_chanmon_cfgs(3);
3439 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3440 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3441 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3442 create_announced_chan_between_nodes(&nodes, 0, 1);
3443 create_announced_chan_between_nodes(&nodes, 1, 2);
3445 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3447 let mut payment_event = {
3448 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3449 check_added_monitors!(nodes[0], 1);
3451 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3452 assert_eq!(events.len(), 1);
3453 SendEvent::from_event(events.remove(0))
3456 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3457 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3459 expect_pending_htlcs_forwardable!(nodes[1]);
3461 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3462 assert_eq!(events_2.len(), 1);
3463 payment_event = SendEvent::from_event(events_2.remove(0));
3464 assert_eq!(payment_event.msgs.len(), 1);
3466 check_added_monitors!(nodes[1], 1);
3467 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3468 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3469 check_added_monitors!(nodes[2], 1);
3470 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3472 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3473 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3474 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3476 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3477 check_closed_broadcast!(nodes[2], true);
3478 check_added_monitors!(nodes[2], 1);
3479 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3481 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3482 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3483 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3484 // back to nodes[1] upon timeout otherwise.
3485 assert_eq!(node_txn.len(), 1);
3489 mine_transaction(&nodes[1], &tx);
3491 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3492 check_closed_broadcast!(nodes[1], true);
3493 check_added_monitors!(nodes[1], 1);
3494 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3496 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3498 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3499 .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);
3501 mine_transaction(&nodes[2], &tx);
3502 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3503 assert_eq!(node_txn.len(), 1);
3504 assert_eq!(node_txn[0].input.len(), 1);
3505 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3506 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3507 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3509 check_spends!(node_txn[0], tx);
3513 fn test_dup_events_on_peer_disconnect() {
3514 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3515 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3516 // as we used to generate the event immediately upon receipt of the payment preimage in the
3517 // update_fulfill_htlc message.
3519 let chanmon_cfgs = create_chanmon_cfgs(2);
3520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3523 create_announced_chan_between_nodes(&nodes, 0, 1);
3525 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3527 nodes[1].node.claim_funds(payment_preimage);
3528 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3529 check_added_monitors!(nodes[1], 1);
3530 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3531 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3532 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3534 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3535 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3537 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3538 expect_payment_path_successful!(nodes[0]);
3542 fn test_peer_disconnected_before_funding_broadcasted() {
3543 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3544 // before the funding transaction has been broadcasted.
3545 let chanmon_cfgs = create_chanmon_cfgs(2);
3546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3550 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3551 // broadcasted, even though it's created by `nodes[0]`.
3552 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();
3553 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3554 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3555 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3556 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3558 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3559 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3561 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3563 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3564 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3566 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3567 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3570 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3573 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3574 // disconnected before the funding transaction was broadcasted.
3575 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3576 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3578 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3579 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3583 fn test_simple_peer_disconnect() {
3584 // Test that we can reconnect when there are no lost messages
3585 let chanmon_cfgs = create_chanmon_cfgs(3);
3586 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3587 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3588 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3589 create_announced_chan_between_nodes(&nodes, 0, 1);
3590 create_announced_chan_between_nodes(&nodes, 1, 2);
3592 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3593 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3594 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3597 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3598 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3599 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3601 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3602 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3603 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3605 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3606 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3607 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3608 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3610 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3611 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3613 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3614 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3616 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3618 let events = nodes[0].node.get_and_clear_pending_events();
3619 assert_eq!(events.len(), 4);
3621 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3622 assert_eq!(payment_preimage, payment_preimage_3);
3623 assert_eq!(payment_hash, payment_hash_3);
3625 _ => panic!("Unexpected event"),
3628 Event::PaymentPathSuccessful { .. } => {},
3629 _ => panic!("Unexpected event"),
3632 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3633 assert_eq!(payment_hash, payment_hash_5);
3634 assert!(payment_failed_permanently);
3636 _ => panic!("Unexpected event"),
3639 Event::PaymentFailed { payment_hash, .. } => {
3640 assert_eq!(payment_hash, payment_hash_5);
3642 _ => panic!("Unexpected event"),
3646 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3647 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3650 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3651 // Test that we can reconnect when in-flight HTLC updates get dropped
3652 let chanmon_cfgs = create_chanmon_cfgs(2);
3653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3655 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3657 let mut as_channel_ready = None;
3658 let channel_id = if messages_delivered == 0 {
3659 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3660 as_channel_ready = Some(channel_ready);
3661 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3662 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3663 // it before the channel_reestablish message.
3666 create_announced_chan_between_nodes(&nodes, 0, 1).2
3669 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3671 let payment_event = {
3672 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3673 check_added_monitors!(nodes[0], 1);
3675 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3676 assert_eq!(events.len(), 1);
3677 SendEvent::from_event(events.remove(0))
3679 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3681 if messages_delivered < 2 {
3682 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3684 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3685 if messages_delivered >= 3 {
3686 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3687 check_added_monitors!(nodes[1], 1);
3688 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3690 if messages_delivered >= 4 {
3691 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3692 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3693 check_added_monitors!(nodes[0], 1);
3695 if messages_delivered >= 5 {
3696 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3697 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3698 // No commitment_signed so get_event_msg's assert(len == 1) passes
3699 check_added_monitors!(nodes[0], 1);
3701 if messages_delivered >= 6 {
3702 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3703 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3704 check_added_monitors!(nodes[1], 1);
3711 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3712 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3713 if messages_delivered < 3 {
3714 if simulate_broken_lnd {
3715 // lnd has a long-standing bug where they send a channel_ready prior to a
3716 // channel_reestablish if you reconnect prior to channel_ready time.
3718 // Here we simulate that behavior, delivering a channel_ready immediately on
3719 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3720 // in `reconnect_nodes` but we currently don't fail based on that.
3722 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3723 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3725 // Even if the channel_ready messages get exchanged, as long as nothing further was
3726 // received on either side, both sides will need to resend them.
3727 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3728 } else if messages_delivered == 3 {
3729 // nodes[0] still wants its RAA + commitment_signed
3730 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3731 } else if messages_delivered == 4 {
3732 // nodes[0] still wants its commitment_signed
3733 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734 } else if messages_delivered == 5 {
3735 // nodes[1] still wants its final RAA
3736 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3737 } else if messages_delivered == 6 {
3738 // Everything was delivered...
3739 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3742 let events_1 = nodes[1].node.get_and_clear_pending_events();
3743 if messages_delivered == 0 {
3744 assert_eq!(events_1.len(), 2);
3746 Event::ChannelReady { .. } => { },
3747 _ => panic!("Unexpected event"),
3750 Event::PendingHTLCsForwardable { .. } => { },
3751 _ => panic!("Unexpected event"),
3754 assert_eq!(events_1.len(), 1);
3756 Event::PendingHTLCsForwardable { .. } => { },
3757 _ => panic!("Unexpected event"),
3761 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3762 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3763 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3765 nodes[1].node.process_pending_htlc_forwards();
3767 let events_2 = nodes[1].node.get_and_clear_pending_events();
3768 assert_eq!(events_2.len(), 1);
3770 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3771 assert_eq!(payment_hash_1, *payment_hash);
3772 assert_eq!(amount_msat, 1_000_000);
3773 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3774 assert_eq!(via_channel_id, Some(channel_id));
3776 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3777 assert!(payment_preimage.is_none());
3778 assert_eq!(payment_secret_1, *payment_secret);
3780 _ => panic!("expected PaymentPurpose::InvoicePayment")
3783 _ => panic!("Unexpected event"),
3786 nodes[1].node.claim_funds(payment_preimage_1);
3787 check_added_monitors!(nodes[1], 1);
3788 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3790 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3791 assert_eq!(events_3.len(), 1);
3792 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3793 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3794 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3795 assert!(updates.update_add_htlcs.is_empty());
3796 assert!(updates.update_fail_htlcs.is_empty());
3797 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3798 assert!(updates.update_fail_malformed_htlcs.is_empty());
3799 assert!(updates.update_fee.is_none());
3800 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3802 _ => panic!("Unexpected event"),
3805 if messages_delivered >= 1 {
3806 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3808 let events_4 = nodes[0].node.get_and_clear_pending_events();
3809 assert_eq!(events_4.len(), 1);
3811 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3812 assert_eq!(payment_preimage_1, *payment_preimage);
3813 assert_eq!(payment_hash_1, *payment_hash);
3815 _ => panic!("Unexpected event"),
3818 if messages_delivered >= 2 {
3819 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3820 check_added_monitors!(nodes[0], 1);
3821 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3823 if messages_delivered >= 3 {
3824 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3825 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3826 check_added_monitors!(nodes[1], 1);
3828 if messages_delivered >= 4 {
3829 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3830 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3831 // No commitment_signed so get_event_msg's assert(len == 1) passes
3832 check_added_monitors!(nodes[1], 1);
3834 if messages_delivered >= 5 {
3835 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3836 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3837 check_added_monitors!(nodes[0], 1);
3844 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3845 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3846 if messages_delivered < 2 {
3847 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3848 if messages_delivered < 1 {
3849 expect_payment_sent!(nodes[0], payment_preimage_1);
3851 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3853 } else if messages_delivered == 2 {
3854 // nodes[0] still wants its RAA + commitment_signed
3855 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3856 } else if messages_delivered == 3 {
3857 // nodes[0] still wants its commitment_signed
3858 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3859 } else if messages_delivered == 4 {
3860 // nodes[1] still wants its final RAA
3861 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3862 } else if messages_delivered == 5 {
3863 // Everything was delivered...
3864 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3867 if messages_delivered == 1 || messages_delivered == 2 {
3868 expect_payment_path_successful!(nodes[0]);
3870 if messages_delivered <= 5 {
3871 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3872 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3874 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3876 if messages_delivered > 2 {
3877 expect_payment_path_successful!(nodes[0]);
3880 // Channel should still work fine...
3881 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3882 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3883 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3887 fn test_drop_messages_peer_disconnect_a() {
3888 do_test_drop_messages_peer_disconnect(0, true);
3889 do_test_drop_messages_peer_disconnect(0, false);
3890 do_test_drop_messages_peer_disconnect(1, false);
3891 do_test_drop_messages_peer_disconnect(2, false);
3895 fn test_drop_messages_peer_disconnect_b() {
3896 do_test_drop_messages_peer_disconnect(3, false);
3897 do_test_drop_messages_peer_disconnect(4, false);
3898 do_test_drop_messages_peer_disconnect(5, false);
3899 do_test_drop_messages_peer_disconnect(6, false);
3903 fn test_channel_ready_without_best_block_updated() {
3904 // Previously, if we were offline when a funding transaction was locked in, and then we came
3905 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3906 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3907 // channel_ready immediately instead.
3908 let chanmon_cfgs = create_chanmon_cfgs(2);
3909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3911 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3912 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3914 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3916 let conf_height = nodes[0].best_block_info().1 + 1;
3917 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3918 let block_txn = [funding_tx];
3919 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3920 let conf_block_header = nodes[0].get_block_header(conf_height);
3921 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3923 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3924 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3925 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3929 fn test_drop_messages_peer_disconnect_dual_htlc() {
3930 // Test that we can handle reconnecting when both sides of a channel have pending
3931 // commitment_updates when we disconnect.
3932 let chanmon_cfgs = create_chanmon_cfgs(2);
3933 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3934 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3935 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3936 create_announced_chan_between_nodes(&nodes, 0, 1);
3938 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3940 // Now try to send a second payment which will fail to send
3941 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3942 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3943 check_added_monitors!(nodes[0], 1);
3945 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3946 assert_eq!(events_1.len(), 1);
3948 MessageSendEvent::UpdateHTLCs { .. } => {},
3949 _ => panic!("Unexpected event"),
3952 nodes[1].node.claim_funds(payment_preimage_1);
3953 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3954 check_added_monitors!(nodes[1], 1);
3956 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3957 assert_eq!(events_2.len(), 1);
3959 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 } } => {
3960 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3961 assert!(update_add_htlcs.is_empty());
3962 assert_eq!(update_fulfill_htlcs.len(), 1);
3963 assert!(update_fail_htlcs.is_empty());
3964 assert!(update_fail_malformed_htlcs.is_empty());
3965 assert!(update_fee.is_none());
3967 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3968 let events_3 = nodes[0].node.get_and_clear_pending_events();
3969 assert_eq!(events_3.len(), 1);
3971 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3972 assert_eq!(*payment_preimage, payment_preimage_1);
3973 assert_eq!(*payment_hash, payment_hash_1);
3975 _ => panic!("Unexpected event"),
3978 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3979 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3980 // No commitment_signed so get_event_msg's assert(len == 1) passes
3981 check_added_monitors!(nodes[0], 1);
3983 _ => panic!("Unexpected event"),
3986 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3987 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3989 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();
3990 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3991 assert_eq!(reestablish_1.len(), 1);
3992 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();
3993 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3994 assert_eq!(reestablish_2.len(), 1);
3996 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3997 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3998 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3999 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4001 assert!(as_resp.0.is_none());
4002 assert!(bs_resp.0.is_none());
4004 assert!(bs_resp.1.is_none());
4005 assert!(bs_resp.2.is_none());
4007 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4009 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4010 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4011 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4012 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4013 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4014 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4015 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4016 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4017 // No commitment_signed so get_event_msg's assert(len == 1) passes
4018 check_added_monitors!(nodes[1], 1);
4020 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4021 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4022 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4023 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4024 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4025 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4026 assert!(bs_second_commitment_signed.update_fee.is_none());
4027 check_added_monitors!(nodes[1], 1);
4029 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4030 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4031 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4032 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4033 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4034 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4035 assert!(as_commitment_signed.update_fee.is_none());
4036 check_added_monitors!(nodes[0], 1);
4038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4039 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4040 // No commitment_signed so get_event_msg's assert(len == 1) passes
4041 check_added_monitors!(nodes[0], 1);
4043 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4044 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4045 // No commitment_signed so get_event_msg's assert(len == 1) passes
4046 check_added_monitors!(nodes[1], 1);
4048 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4049 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4050 check_added_monitors!(nodes[1], 1);
4052 expect_pending_htlcs_forwardable!(nodes[1]);
4054 let events_5 = nodes[1].node.get_and_clear_pending_events();
4055 assert_eq!(events_5.len(), 1);
4057 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4058 assert_eq!(payment_hash_2, *payment_hash);
4060 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4061 assert!(payment_preimage.is_none());
4062 assert_eq!(payment_secret_2, *payment_secret);
4064 _ => panic!("expected PaymentPurpose::InvoicePayment")
4067 _ => panic!("Unexpected event"),
4070 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4071 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4072 check_added_monitors!(nodes[0], 1);
4074 expect_payment_path_successful!(nodes[0]);
4075 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4078 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4079 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4080 // to avoid our counterparty failing the channel.
4081 let chanmon_cfgs = create_chanmon_cfgs(2);
4082 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4083 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4084 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4086 create_announced_chan_between_nodes(&nodes, 0, 1);
4088 let our_payment_hash = if send_partial_mpp {
4089 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4090 // Use the utility function send_payment_along_path to send the payment with MPP data which
4091 // indicates there are more HTLCs coming.
4092 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.
4093 let payment_id = PaymentId([42; 32]);
4094 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4095 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();
4096 check_added_monitors!(nodes[0], 1);
4097 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4098 assert_eq!(events.len(), 1);
4099 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4100 // hop should *not* yet generate any PaymentClaimable event(s).
4101 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4104 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4107 let mut block = Block {
4108 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4111 connect_block(&nodes[0], &block);
4112 connect_block(&nodes[1], &block);
4113 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4114 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4115 block.header.prev_blockhash = block.block_hash();
4116 connect_block(&nodes[0], &block);
4117 connect_block(&nodes[1], &block);
4120 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4122 check_added_monitors!(nodes[1], 1);
4123 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4124 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4125 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4126 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4127 assert!(htlc_timeout_updates.update_fee.is_none());
4129 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4130 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4131 // 100_000 msat as u64, followed by the height at which we failed back above
4132 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4133 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4134 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4138 fn test_htlc_timeout() {
4139 do_test_htlc_timeout(true);
4140 do_test_htlc_timeout(false);
4143 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4144 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4145 let chanmon_cfgs = create_chanmon_cfgs(3);
4146 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4147 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4148 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4149 create_announced_chan_between_nodes(&nodes, 0, 1);
4150 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4152 // Make sure all nodes are at the same starting height
4153 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4154 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4155 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4157 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4158 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4160 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4162 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4163 check_added_monitors!(nodes[1], 1);
4165 // Now attempt to route a second payment, which should be placed in the holding cell
4166 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4167 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4168 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4170 check_added_monitors!(nodes[0], 1);
4171 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4172 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4173 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4174 expect_pending_htlcs_forwardable!(nodes[1]);
4176 check_added_monitors!(nodes[1], 0);
4178 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4179 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4180 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4181 connect_blocks(&nodes[1], 1);
4184 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 }]);
4185 check_added_monitors!(nodes[1], 1);
4186 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4187 assert_eq!(fail_commit.len(), 1);
4188 match fail_commit[0] {
4189 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4190 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4191 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4193 _ => unreachable!(),
4195 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4197 expect_payment_failed!(nodes[1], second_payment_hash, false);
4202 fn test_holding_cell_htlc_add_timeouts() {
4203 do_test_holding_cell_htlc_add_timeouts(false);
4204 do_test_holding_cell_htlc_add_timeouts(true);
4207 macro_rules! check_spendable_outputs {
4208 ($node: expr, $keysinterface: expr) => {
4210 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4211 let mut txn = Vec::new();
4212 let mut all_outputs = Vec::new();
4213 let secp_ctx = Secp256k1::new();
4214 for event in events.drain(..) {
4216 Event::SpendableOutputs { mut outputs } => {
4217 for outp in outputs.drain(..) {
4218 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4219 all_outputs.push(outp);
4222 _ => panic!("Unexpected event"),
4225 if all_outputs.len() > 1 {
4226 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) {
4236 fn test_claim_sizeable_push_msat() {
4237 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4238 let chanmon_cfgs = create_chanmon_cfgs(2);
4239 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4240 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4241 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4243 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4244 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4245 check_closed_broadcast!(nodes[1], true);
4246 check_added_monitors!(nodes[1], 1);
4247 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4248 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4249 assert_eq!(node_txn.len(), 1);
4250 check_spends!(node_txn[0], chan.3);
4251 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
4253 mine_transaction(&nodes[1], &node_txn[0]);
4254 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4256 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4257 assert_eq!(spend_txn.len(), 1);
4258 assert_eq!(spend_txn[0].input.len(), 1);
4259 check_spends!(spend_txn[0], node_txn[0]);
4260 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4264 fn test_claim_on_remote_sizeable_push_msat() {
4265 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4266 // to_remote output is encumbered by a P2WPKH
4267 let chanmon_cfgs = create_chanmon_cfgs(2);
4268 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4269 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4270 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4272 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4273 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4274 check_closed_broadcast!(nodes[0], true);
4275 check_added_monitors!(nodes[0], 1);
4276 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4278 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4279 assert_eq!(node_txn.len(), 1);
4280 check_spends!(node_txn[0], chan.3);
4281 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
4283 mine_transaction(&nodes[1], &node_txn[0]);
4284 check_closed_broadcast!(nodes[1], true);
4285 check_added_monitors!(nodes[1], 1);
4286 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4287 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4289 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4290 assert_eq!(spend_txn.len(), 1);
4291 check_spends!(spend_txn[0], node_txn[0]);
4295 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4296 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4297 // to_remote output is encumbered by a P2WPKH
4299 let chanmon_cfgs = create_chanmon_cfgs(2);
4300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4302 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4304 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4305 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4306 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4307 assert_eq!(revoked_local_txn[0].input.len(), 1);
4308 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4310 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4311 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4312 check_closed_broadcast!(nodes[1], true);
4313 check_added_monitors!(nodes[1], 1);
4314 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4316 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4317 mine_transaction(&nodes[1], &node_txn[0]);
4318 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4320 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4321 assert_eq!(spend_txn.len(), 3);
4322 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4323 check_spends!(spend_txn[1], node_txn[0]);
4324 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4328 fn test_static_spendable_outputs_preimage_tx() {
4329 let chanmon_cfgs = create_chanmon_cfgs(2);
4330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4334 // Create some initial channels
4335 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4337 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4339 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4340 assert_eq!(commitment_tx[0].input.len(), 1);
4341 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4343 // Settle A's commitment tx on B's chain
4344 nodes[1].node.claim_funds(payment_preimage);
4345 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4346 check_added_monitors!(nodes[1], 1);
4347 mine_transaction(&nodes[1], &commitment_tx[0]);
4348 check_added_monitors!(nodes[1], 1);
4349 let events = nodes[1].node.get_and_clear_pending_msg_events();
4351 MessageSendEvent::UpdateHTLCs { .. } => {},
4352 _ => panic!("Unexpected event"),
4355 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4356 _ => panic!("Unexepected event"),
4359 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4360 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4361 assert_eq!(node_txn.len(), 1);
4362 check_spends!(node_txn[0], commitment_tx[0]);
4363 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4365 mine_transaction(&nodes[1], &node_txn[0]);
4366 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4367 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4369 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4370 assert_eq!(spend_txn.len(), 1);
4371 check_spends!(spend_txn[0], node_txn[0]);
4375 fn test_static_spendable_outputs_timeout_tx() {
4376 let chanmon_cfgs = create_chanmon_cfgs(2);
4377 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4378 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4379 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4381 // Create some initial channels
4382 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4384 // Rebalance the network a bit by relaying one payment through all the channels ...
4385 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4387 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4389 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4390 assert_eq!(commitment_tx[0].input.len(), 1);
4391 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4393 // Settle A's commitment tx on B' chain
4394 mine_transaction(&nodes[1], &commitment_tx[0]);
4395 check_added_monitors!(nodes[1], 1);
4396 let events = nodes[1].node.get_and_clear_pending_msg_events();
4398 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4399 _ => panic!("Unexpected event"),
4401 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4403 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4404 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4405 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4406 check_spends!(node_txn[0], commitment_tx[0].clone());
4407 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4409 mine_transaction(&nodes[1], &node_txn[0]);
4410 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4411 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4412 expect_payment_failed!(nodes[1], our_payment_hash, false);
4414 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4415 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4416 check_spends!(spend_txn[0], commitment_tx[0]);
4417 check_spends!(spend_txn[1], node_txn[0]);
4418 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4422 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4423 let chanmon_cfgs = create_chanmon_cfgs(2);
4424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4426 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4428 // Create some initial channels
4429 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4431 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4432 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4433 assert_eq!(revoked_local_txn[0].input.len(), 1);
4434 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4436 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4438 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4439 check_closed_broadcast!(nodes[1], true);
4440 check_added_monitors!(nodes[1], 1);
4441 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4443 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4444 assert_eq!(node_txn.len(), 1);
4445 assert_eq!(node_txn[0].input.len(), 2);
4446 check_spends!(node_txn[0], revoked_local_txn[0]);
4448 mine_transaction(&nodes[1], &node_txn[0]);
4449 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4451 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4452 assert_eq!(spend_txn.len(), 1);
4453 check_spends!(spend_txn[0], node_txn[0]);
4457 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4458 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4459 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4464 // Create some initial channels
4465 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4467 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4468 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4469 assert_eq!(revoked_local_txn[0].input.len(), 1);
4470 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4472 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4474 // A will generate HTLC-Timeout from revoked commitment tx
4475 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4476 check_closed_broadcast!(nodes[0], true);
4477 check_added_monitors!(nodes[0], 1);
4478 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4479 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4481 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4482 assert_eq!(revoked_htlc_txn.len(), 1);
4483 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4484 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4485 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4486 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4488 // B will generate justice tx from A's revoked commitment/HTLC tx
4489 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4490 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4491 check_closed_broadcast!(nodes[1], true);
4492 check_added_monitors!(nodes[1], 1);
4493 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4495 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4496 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4497 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4498 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4499 // transactions next...
4500 assert_eq!(node_txn[0].input.len(), 3);
4501 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4503 assert_eq!(node_txn[1].input.len(), 2);
4504 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4505 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4506 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4508 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4509 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4512 mine_transaction(&nodes[1], &node_txn[1]);
4513 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4515 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4516 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4517 assert_eq!(spend_txn.len(), 1);
4518 assert_eq!(spend_txn[0].input.len(), 1);
4519 check_spends!(spend_txn[0], node_txn[1]);
4523 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4524 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4525 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4528 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4530 // Create some initial channels
4531 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4533 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4534 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4535 assert_eq!(revoked_local_txn[0].input.len(), 1);
4536 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4538 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4539 assert_eq!(revoked_local_txn[0].output.len(), 2);
4541 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4543 // B will generate HTLC-Success from revoked commitment tx
4544 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4545 check_closed_broadcast!(nodes[1], true);
4546 check_added_monitors!(nodes[1], 1);
4547 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4548 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4550 assert_eq!(revoked_htlc_txn.len(), 1);
4551 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4552 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4553 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4555 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4556 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4557 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4559 // A will generate justice tx from B's revoked commitment/HTLC tx
4560 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4561 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4562 check_closed_broadcast!(nodes[0], true);
4563 check_added_monitors!(nodes[0], 1);
4564 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4566 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4567 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4569 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4570 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4571 // transactions next...
4572 assert_eq!(node_txn[0].input.len(), 2);
4573 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4574 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4575 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4577 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4578 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4581 assert_eq!(node_txn[1].input.len(), 1);
4582 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4584 mine_transaction(&nodes[0], &node_txn[1]);
4585 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4587 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4588 // didn't try to generate any new transactions.
4590 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4591 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4592 assert_eq!(spend_txn.len(), 3);
4593 assert_eq!(spend_txn[0].input.len(), 1);
4594 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4595 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4596 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4597 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4601 fn test_onchain_to_onchain_claim() {
4602 // Test that in case of channel closure, we detect the state of output and claim HTLC
4603 // on downstream peer's remote commitment tx.
4604 // First, have C claim an HTLC against its own latest commitment transaction.
4605 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4607 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4610 let chanmon_cfgs = create_chanmon_cfgs(3);
4611 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4612 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4613 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4615 // Create some initial channels
4616 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4617 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4619 // Ensure all nodes are at the same height
4620 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4621 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4622 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4623 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4625 // Rebalance the network a bit by relaying one payment through all the channels ...
4626 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4627 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4629 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4630 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4631 check_spends!(commitment_tx[0], chan_2.3);
4632 nodes[2].node.claim_funds(payment_preimage);
4633 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4634 check_added_monitors!(nodes[2], 1);
4635 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4636 assert!(updates.update_add_htlcs.is_empty());
4637 assert!(updates.update_fail_htlcs.is_empty());
4638 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4639 assert!(updates.update_fail_malformed_htlcs.is_empty());
4641 mine_transaction(&nodes[2], &commitment_tx[0]);
4642 check_closed_broadcast!(nodes[2], true);
4643 check_added_monitors!(nodes[2], 1);
4644 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4646 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4647 assert_eq!(c_txn.len(), 1);
4648 check_spends!(c_txn[0], commitment_tx[0]);
4649 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4650 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4651 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4653 // 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
4654 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4655 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4656 check_added_monitors!(nodes[1], 1);
4657 let events = nodes[1].node.get_and_clear_pending_events();
4658 assert_eq!(events.len(), 2);
4660 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4661 _ => panic!("Unexpected event"),
4664 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4665 assert_eq!(fee_earned_msat, Some(1000));
4666 assert_eq!(prev_channel_id, Some(chan_1.2));
4667 assert_eq!(claim_from_onchain_tx, true);
4668 assert_eq!(next_channel_id, Some(chan_2.2));
4669 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4671 _ => panic!("Unexpected event"),
4673 check_added_monitors!(nodes[1], 1);
4674 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4675 assert_eq!(msg_events.len(), 3);
4676 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4677 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4679 match nodes_2_event {
4680 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4681 _ => panic!("Unexpected event"),
4684 match nodes_0_event {
4685 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, .. } } => {
4686 assert!(update_add_htlcs.is_empty());
4687 assert!(update_fail_htlcs.is_empty());
4688 assert_eq!(update_fulfill_htlcs.len(), 1);
4689 assert!(update_fail_malformed_htlcs.is_empty());
4690 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4692 _ => panic!("Unexpected event"),
4695 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4696 match msg_events[0] {
4697 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4698 _ => panic!("Unexpected event"),
4701 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4702 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4703 mine_transaction(&nodes[1], &commitment_tx[0]);
4704 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4705 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4706 // ChannelMonitor: HTLC-Success tx
4707 assert_eq!(b_txn.len(), 1);
4708 check_spends!(b_txn[0], commitment_tx[0]);
4709 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4710 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4711 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4713 check_closed_broadcast!(nodes[1], true);
4714 check_added_monitors!(nodes[1], 1);
4718 fn test_duplicate_payment_hash_one_failure_one_success() {
4719 // Topology : A --> B --> C --> D
4720 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4721 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4722 // we forward one of the payments onwards to D.
4723 let chanmon_cfgs = create_chanmon_cfgs(4);
4724 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4725 // When this test was written, the default base fee floated based on the HTLC count.
4726 // It is now fixed, so we simply set the fee to the expected value here.
4727 let mut config = test_default_channel_config();
4728 config.channel_config.forwarding_fee_base_msat = 196;
4729 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4730 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4731 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4733 create_announced_chan_between_nodes(&nodes, 0, 1);
4734 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4735 create_announced_chan_between_nodes(&nodes, 2, 3);
4737 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4738 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4739 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4740 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4741 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4743 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4745 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4746 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4747 // script push size limit so that the below script length checks match
4748 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4749 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4750 .with_features(nodes[3].node.invoice_features());
4751 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4752 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4754 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4755 assert_eq!(commitment_txn[0].input.len(), 1);
4756 check_spends!(commitment_txn[0], chan_2.3);
4758 mine_transaction(&nodes[1], &commitment_txn[0]);
4759 check_closed_broadcast!(nodes[1], true);
4760 check_added_monitors!(nodes[1], 1);
4761 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4762 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4764 let htlc_timeout_tx;
4765 { // Extract one of the two HTLC-Timeout transaction
4766 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4767 // ChannelMonitor: timeout tx * 2-or-3
4768 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4770 check_spends!(node_txn[0], commitment_txn[0]);
4771 assert_eq!(node_txn[0].input.len(), 1);
4772 assert_eq!(node_txn[0].output.len(), 1);
4774 if node_txn.len() > 2 {
4775 check_spends!(node_txn[1], commitment_txn[0]);
4776 assert_eq!(node_txn[1].input.len(), 1);
4777 assert_eq!(node_txn[1].output.len(), 1);
4778 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4780 check_spends!(node_txn[2], commitment_txn[0]);
4781 assert_eq!(node_txn[2].input.len(), 1);
4782 assert_eq!(node_txn[2].output.len(), 1);
4783 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4785 check_spends!(node_txn[1], commitment_txn[0]);
4786 assert_eq!(node_txn[1].input.len(), 1);
4787 assert_eq!(node_txn[1].output.len(), 1);
4788 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4791 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4792 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4793 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4794 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4795 if node_txn.len() > 2 {
4796 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4797 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4799 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4803 nodes[2].node.claim_funds(our_payment_preimage);
4804 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4806 mine_transaction(&nodes[2], &commitment_txn[0]);
4807 check_added_monitors!(nodes[2], 2);
4808 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4809 let events = nodes[2].node.get_and_clear_pending_msg_events();
4811 MessageSendEvent::UpdateHTLCs { .. } => {},
4812 _ => panic!("Unexpected event"),
4815 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4816 _ => panic!("Unexepected event"),
4818 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4819 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4820 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4821 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4822 assert_eq!(htlc_success_txn[0].input.len(), 1);
4823 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4824 assert_eq!(htlc_success_txn[1].input.len(), 1);
4825 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4826 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4827 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4829 mine_transaction(&nodes[1], &htlc_timeout_tx);
4830 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4831 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 }]);
4832 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4833 assert!(htlc_updates.update_add_htlcs.is_empty());
4834 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4835 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4836 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4837 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4838 check_added_monitors!(nodes[1], 1);
4840 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4843 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4845 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4847 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4848 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4849 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4850 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4851 assert!(updates.update_add_htlcs.is_empty());
4852 assert!(updates.update_fail_htlcs.is_empty());
4853 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4854 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4855 assert!(updates.update_fail_malformed_htlcs.is_empty());
4856 check_added_monitors!(nodes[1], 1);
4858 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4859 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4861 let events = nodes[0].node.get_and_clear_pending_events();
4863 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4864 assert_eq!(*payment_preimage, our_payment_preimage);
4865 assert_eq!(*payment_hash, duplicate_payment_hash);
4867 _ => panic!("Unexpected event"),
4872 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4873 let chanmon_cfgs = create_chanmon_cfgs(2);
4874 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4875 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4876 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4878 // Create some initial channels
4879 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4881 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4882 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4883 assert_eq!(local_txn.len(), 1);
4884 assert_eq!(local_txn[0].input.len(), 1);
4885 check_spends!(local_txn[0], chan_1.3);
4887 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4888 nodes[1].node.claim_funds(payment_preimage);
4889 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4890 check_added_monitors!(nodes[1], 1);
4892 mine_transaction(&nodes[1], &local_txn[0]);
4893 check_added_monitors!(nodes[1], 1);
4894 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4895 let events = nodes[1].node.get_and_clear_pending_msg_events();
4897 MessageSendEvent::UpdateHTLCs { .. } => {},
4898 _ => panic!("Unexpected event"),
4901 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4902 _ => panic!("Unexepected event"),
4905 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4906 assert_eq!(node_txn.len(), 1);
4907 assert_eq!(node_txn[0].input.len(), 1);
4908 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4909 check_spends!(node_txn[0], local_txn[0]);
4913 mine_transaction(&nodes[1], &node_tx);
4914 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4916 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4917 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4918 assert_eq!(spend_txn.len(), 1);
4919 assert_eq!(spend_txn[0].input.len(), 1);
4920 check_spends!(spend_txn[0], node_tx);
4921 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4924 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4925 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4926 // unrevoked commitment transaction.
4927 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4928 // a remote RAA before they could be failed backwards (and combinations thereof).
4929 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4930 // use the same payment hashes.
4931 // Thus, we use a six-node network:
4936 // And test where C fails back to A/B when D announces its latest commitment transaction
4937 let chanmon_cfgs = create_chanmon_cfgs(6);
4938 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4939 // When this test was written, the default base fee floated based on the HTLC count.
4940 // It is now fixed, so we simply set the fee to the expected value here.
4941 let mut config = test_default_channel_config();
4942 config.channel_config.forwarding_fee_base_msat = 196;
4943 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4944 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4945 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4947 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4948 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4949 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4950 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4951 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4953 // Rebalance and check output sanity...
4954 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4955 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4956 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4958 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4959 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4961 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
4963 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
4964 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4966 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
4968 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
4970 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4972 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4973 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4975 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());
4977 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());
4980 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4982 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4983 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
4986 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
4988 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4989 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());
4991 // Double-check that six of the new HTLC were added
4992 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4993 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4994 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4995 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4997 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4998 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4999 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5000 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5001 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5002 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5003 check_added_monitors!(nodes[4], 0);
5005 let failed_destinations = vec![
5006 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5007 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5008 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5009 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5011 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5012 check_added_monitors!(nodes[4], 1);
5014 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5015 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5016 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5017 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5018 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5019 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5021 // Fail 3rd below-dust and 7th above-dust HTLCs
5022 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5023 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5024 check_added_monitors!(nodes[5], 0);
5026 let failed_destinations_2 = vec![
5027 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5028 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5030 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5031 check_added_monitors!(nodes[5], 1);
5033 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5034 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5035 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5036 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5038 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5040 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5041 let failed_destinations_3 = vec![
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[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5044 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5045 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5046 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5047 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5049 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5050 check_added_monitors!(nodes[3], 1);
5051 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5052 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5053 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5054 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5055 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5056 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5057 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5058 if deliver_last_raa {
5059 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5061 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5064 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5065 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5066 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5067 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5069 // We now broadcast the latest commitment transaction, which *should* result in failures for
5070 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5071 // the non-broadcast above-dust HTLCs.
5073 // Alternatively, we may broadcast the previous commitment transaction, which should only
5074 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5075 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5077 if announce_latest {
5078 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5080 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5082 let events = nodes[2].node.get_and_clear_pending_events();
5083 let close_event = if deliver_last_raa {
5084 assert_eq!(events.len(), 2 + 6);
5085 events.last().clone().unwrap()
5087 assert_eq!(events.len(), 1);
5088 events.last().clone().unwrap()
5091 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5092 _ => panic!("Unexpected event"),
5095 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5096 check_closed_broadcast!(nodes[2], true);
5097 if deliver_last_raa {
5098 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5100 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();
5101 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5103 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5104 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5106 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5109 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5111 check_added_monitors!(nodes[2], 3);
5113 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5114 assert_eq!(cs_msgs.len(), 2);
5115 let mut a_done = false;
5116 for msg in cs_msgs {
5118 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5119 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5120 // should be failed-backwards here.
5121 let target = if *node_id == nodes[0].node.get_our_node_id() {
5122 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5123 for htlc in &updates.update_fail_htlcs {
5124 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 });
5126 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5131 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5132 for htlc in &updates.update_fail_htlcs {
5133 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5135 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5136 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5139 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5140 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5141 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5142 if announce_latest {
5143 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5144 if *node_id == nodes[0].node.get_our_node_id() {
5145 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5148 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5150 _ => panic!("Unexpected event"),
5154 let as_events = nodes[0].node.get_and_clear_pending_events();
5155 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5156 let mut as_failds = HashSet::new();
5157 let mut as_updates = 0;
5158 for event in as_events.iter() {
5159 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5160 assert!(as_failds.insert(*payment_hash));
5161 if *payment_hash != payment_hash_2 {
5162 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5164 assert!(!payment_failed_permanently);
5166 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5169 } else if let &Event::PaymentFailed { .. } = event {
5170 } else { panic!("Unexpected event"); }
5172 assert!(as_failds.contains(&payment_hash_1));
5173 assert!(as_failds.contains(&payment_hash_2));
5174 if announce_latest {
5175 assert!(as_failds.contains(&payment_hash_3));
5176 assert!(as_failds.contains(&payment_hash_5));
5178 assert!(as_failds.contains(&payment_hash_6));
5180 let bs_events = nodes[1].node.get_and_clear_pending_events();
5181 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5182 let mut bs_failds = HashSet::new();
5183 let mut bs_updates = 0;
5184 for event in bs_events.iter() {
5185 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5186 assert!(bs_failds.insert(*payment_hash));
5187 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5188 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5190 assert!(!payment_failed_permanently);
5192 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5195 } else if let &Event::PaymentFailed { .. } = event {
5196 } else { panic!("Unexpected event"); }
5198 assert!(bs_failds.contains(&payment_hash_1));
5199 assert!(bs_failds.contains(&payment_hash_2));
5200 if announce_latest {
5201 assert!(bs_failds.contains(&payment_hash_4));
5203 assert!(bs_failds.contains(&payment_hash_5));
5205 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5206 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5207 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5208 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5209 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5210 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5214 fn test_fail_backwards_latest_remote_announce_a() {
5215 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5219 fn test_fail_backwards_latest_remote_announce_b() {
5220 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5224 fn test_fail_backwards_previous_remote_announce() {
5225 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5226 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5227 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5231 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5232 let chanmon_cfgs = create_chanmon_cfgs(2);
5233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5237 // Create some initial channels
5238 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5240 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5241 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5242 assert_eq!(local_txn[0].input.len(), 1);
5243 check_spends!(local_txn[0], chan_1.3);
5245 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5246 mine_transaction(&nodes[0], &local_txn[0]);
5247 check_closed_broadcast!(nodes[0], true);
5248 check_added_monitors!(nodes[0], 1);
5249 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5250 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5252 let htlc_timeout = {
5253 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5254 assert_eq!(node_txn.len(), 1);
5255 assert_eq!(node_txn[0].input.len(), 1);
5256 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5257 check_spends!(node_txn[0], local_txn[0]);
5261 mine_transaction(&nodes[0], &htlc_timeout);
5262 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5263 expect_payment_failed!(nodes[0], our_payment_hash, false);
5265 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5266 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5267 assert_eq!(spend_txn.len(), 3);
5268 check_spends!(spend_txn[0], local_txn[0]);
5269 assert_eq!(spend_txn[1].input.len(), 1);
5270 check_spends!(spend_txn[1], htlc_timeout);
5271 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5272 assert_eq!(spend_txn[2].input.len(), 2);
5273 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5274 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5275 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5279 fn test_key_derivation_params() {
5280 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5281 // manager rotation to test that `channel_keys_id` returned in
5282 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5283 // then derive a `delayed_payment_key`.
5285 let chanmon_cfgs = create_chanmon_cfgs(3);
5287 // We manually create the node configuration to backup the seed.
5288 let seed = [42; 32];
5289 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5290 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);
5291 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5292 let scorer = Mutex::new(test_utils::TestScorer::new());
5293 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5294 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)) };
5295 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5296 node_cfgs.remove(0);
5297 node_cfgs.insert(0, node);
5299 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5300 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5302 // Create some initial channels
5303 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5305 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5306 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5307 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5309 // Ensure all nodes are at the same height
5310 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5311 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5312 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5313 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5315 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5316 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5317 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5318 assert_eq!(local_txn_1[0].input.len(), 1);
5319 check_spends!(local_txn_1[0], chan_1.3);
5321 // We check funding pubkey are unique
5322 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]));
5323 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]));
5324 if from_0_funding_key_0 == from_1_funding_key_0
5325 || from_0_funding_key_0 == from_1_funding_key_1
5326 || from_0_funding_key_1 == from_1_funding_key_0
5327 || from_0_funding_key_1 == from_1_funding_key_1 {
5328 panic!("Funding pubkeys aren't unique");
5331 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5332 mine_transaction(&nodes[0], &local_txn_1[0]);
5333 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5334 check_closed_broadcast!(nodes[0], true);
5335 check_added_monitors!(nodes[0], 1);
5336 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5338 let htlc_timeout = {
5339 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5340 assert_eq!(node_txn.len(), 1);
5341 assert_eq!(node_txn[0].input.len(), 1);
5342 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5343 check_spends!(node_txn[0], local_txn_1[0]);
5347 mine_transaction(&nodes[0], &htlc_timeout);
5348 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5349 expect_payment_failed!(nodes[0], our_payment_hash, false);
5351 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5352 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5353 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5354 assert_eq!(spend_txn.len(), 3);
5355 check_spends!(spend_txn[0], local_txn_1[0]);
5356 assert_eq!(spend_txn[1].input.len(), 1);
5357 check_spends!(spend_txn[1], htlc_timeout);
5358 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5359 assert_eq!(spend_txn[2].input.len(), 2);
5360 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5361 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5362 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5366 fn test_static_output_closing_tx() {
5367 let chanmon_cfgs = create_chanmon_cfgs(2);
5368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5370 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5372 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5374 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5375 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5377 mine_transaction(&nodes[0], &closing_tx);
5378 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5379 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5381 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5382 assert_eq!(spend_txn.len(), 1);
5383 check_spends!(spend_txn[0], closing_tx);
5385 mine_transaction(&nodes[1], &closing_tx);
5386 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5387 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5389 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5390 assert_eq!(spend_txn.len(), 1);
5391 check_spends!(spend_txn[0], closing_tx);
5394 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5395 let chanmon_cfgs = create_chanmon_cfgs(2);
5396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5399 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5401 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5403 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5404 // present in B's local commitment transaction, but none of A's commitment transactions.
5405 nodes[1].node.claim_funds(payment_preimage);
5406 check_added_monitors!(nodes[1], 1);
5407 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5409 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5410 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5411 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5413 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5414 check_added_monitors!(nodes[0], 1);
5415 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5416 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5417 check_added_monitors!(nodes[1], 1);
5419 let starting_block = nodes[1].best_block_info();
5420 let mut block = Block {
5421 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5424 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5425 connect_block(&nodes[1], &block);
5426 block.header.prev_blockhash = block.block_hash();
5428 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5429 check_closed_broadcast!(nodes[1], true);
5430 check_added_monitors!(nodes[1], 1);
5431 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5434 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5435 let chanmon_cfgs = create_chanmon_cfgs(2);
5436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5438 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5439 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5441 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5442 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5443 check_added_monitors!(nodes[0], 1);
5445 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5447 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5448 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5449 // to "time out" the HTLC.
5451 let starting_block = nodes[1].best_block_info();
5452 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5454 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5455 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5456 header.prev_blockhash = header.block_hash();
5458 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5459 check_closed_broadcast!(nodes[0], true);
5460 check_added_monitors!(nodes[0], 1);
5461 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5464 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5465 let chanmon_cfgs = create_chanmon_cfgs(3);
5466 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5467 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5468 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5469 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5471 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5472 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5473 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5474 // actually revoked.
5475 let htlc_value = if use_dust { 50000 } else { 3000000 };
5476 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5477 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5478 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5479 check_added_monitors!(nodes[1], 1);
5481 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5482 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5483 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5484 check_added_monitors!(nodes[0], 1);
5485 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5486 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5487 check_added_monitors!(nodes[1], 1);
5488 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5489 check_added_monitors!(nodes[1], 1);
5490 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5492 if check_revoke_no_close {
5493 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5494 check_added_monitors!(nodes[0], 1);
5497 let starting_block = nodes[1].best_block_info();
5498 let mut block = Block {
5499 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5502 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5503 connect_block(&nodes[0], &block);
5504 block.header.prev_blockhash = block.block_hash();
5506 if !check_revoke_no_close {
5507 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5508 check_closed_broadcast!(nodes[0], true);
5509 check_added_monitors!(nodes[0], 1);
5510 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5512 expect_payment_failed!(nodes[0], our_payment_hash, true);
5516 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5517 // There are only a few cases to test here:
5518 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5519 // broadcastable commitment transactions result in channel closure,
5520 // * its included in an unrevoked-but-previous remote commitment transaction,
5521 // * its included in the latest remote or local commitment transactions.
5522 // We test each of the three possible commitment transactions individually and use both dust and
5524 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5525 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5526 // tested for at least one of the cases in other tests.
5528 fn htlc_claim_single_commitment_only_a() {
5529 do_htlc_claim_local_commitment_only(true);
5530 do_htlc_claim_local_commitment_only(false);
5532 do_htlc_claim_current_remote_commitment_only(true);
5533 do_htlc_claim_current_remote_commitment_only(false);
5537 fn htlc_claim_single_commitment_only_b() {
5538 do_htlc_claim_previous_remote_commitment_only(true, false);
5539 do_htlc_claim_previous_remote_commitment_only(false, false);
5540 do_htlc_claim_previous_remote_commitment_only(true, true);
5541 do_htlc_claim_previous_remote_commitment_only(false, true);
5546 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5547 let chanmon_cfgs = create_chanmon_cfgs(2);
5548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5550 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5551 // Force duplicate randomness for every get-random call
5552 for node in nodes.iter() {
5553 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5556 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5557 let channel_value_satoshis=10000;
5558 let push_msat=10001;
5559 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5560 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5561 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5562 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5564 // Create a second channel with the same random values. This used to panic due to a colliding
5565 // channel_id, but now panics due to a colliding outbound SCID alias.
5566 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5570 fn bolt2_open_channel_sending_node_checks_part2() {
5571 let chanmon_cfgs = create_chanmon_cfgs(2);
5572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5576 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5577 let channel_value_satoshis=2^24;
5578 let push_msat=10001;
5579 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5581 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5582 let channel_value_satoshis=10000;
5583 // Test when push_msat is equal to 1000 * funding_satoshis.
5584 let push_msat=1000*channel_value_satoshis+1;
5585 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5587 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5588 let channel_value_satoshis=10000;
5589 let push_msat=10001;
5590 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
5591 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5592 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5594 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5595 // 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
5596 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5598 // 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.
5599 assert!(BREAKDOWN_TIMEOUT>0);
5600 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5602 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5603 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5604 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5606 // 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.
5607 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5608 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5609 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5610 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5611 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5615 fn bolt2_open_channel_sane_dust_limit() {
5616 let chanmon_cfgs = create_chanmon_cfgs(2);
5617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5619 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5621 let channel_value_satoshis=1000000;
5622 let push_msat=10001;
5623 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5624 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5625 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5626 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5628 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5629 let events = nodes[1].node.get_and_clear_pending_msg_events();
5630 let err_msg = match events[0] {
5631 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5634 _ => panic!("Unexpected event"),
5636 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5639 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5640 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5641 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5642 // is no longer affordable once it's freed.
5644 fn test_fail_holding_cell_htlc_upon_free() {
5645 let chanmon_cfgs = create_chanmon_cfgs(2);
5646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5649 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5651 // First nodes[0] generates an update_fee, setting the channel's
5652 // pending_update_fee.
5654 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5655 *feerate_lock += 20;
5657 nodes[0].node.timer_tick_occurred();
5658 check_added_monitors!(nodes[0], 1);
5660 let events = nodes[0].node.get_and_clear_pending_msg_events();
5661 assert_eq!(events.len(), 1);
5662 let (update_msg, commitment_signed) = match events[0] {
5663 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5664 (update_fee.as_ref(), commitment_signed)
5666 _ => panic!("Unexpected event"),
5669 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5671 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5672 let channel_reserve = chan_stat.channel_reserve_msat;
5673 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5674 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5676 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5677 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5678 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5680 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5681 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5682 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5683 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5685 // Flush the pending fee update.
5686 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5687 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5688 check_added_monitors!(nodes[1], 1);
5689 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5690 check_added_monitors!(nodes[0], 1);
5692 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5693 // HTLC, but now that the fee has been raised the payment will now fail, causing
5694 // us to surface its failure to the user.
5695 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5696 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5697 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);
5698 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 {}",
5699 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5700 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5702 // Check that the payment failed to be sent out.
5703 let events = nodes[0].node.get_and_clear_pending_events();
5704 assert_eq!(events.len(), 2);
5706 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5707 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5708 assert_eq!(our_payment_hash.clone(), *payment_hash);
5709 assert_eq!(*payment_failed_permanently, false);
5710 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5712 _ => panic!("Unexpected event"),
5715 &Event::PaymentFailed { ref payment_hash, .. } => {
5716 assert_eq!(our_payment_hash.clone(), *payment_hash);
5718 _ => panic!("Unexpected event"),
5722 // Test that if multiple HTLCs are released from the holding cell and one is
5723 // valid but the other is no longer valid upon release, the valid HTLC can be
5724 // successfully completed while the other one fails as expected.
5726 fn test_free_and_fail_holding_cell_htlcs() {
5727 let chanmon_cfgs = create_chanmon_cfgs(2);
5728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5731 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5733 // First nodes[0] generates an update_fee, setting the channel's
5734 // pending_update_fee.
5736 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5737 *feerate_lock += 200;
5739 nodes[0].node.timer_tick_occurred();
5740 check_added_monitors!(nodes[0], 1);
5742 let events = nodes[0].node.get_and_clear_pending_msg_events();
5743 assert_eq!(events.len(), 1);
5744 let (update_msg, commitment_signed) = match events[0] {
5745 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5746 (update_fee.as_ref(), commitment_signed)
5748 _ => panic!("Unexpected event"),
5751 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5753 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5754 let channel_reserve = chan_stat.channel_reserve_msat;
5755 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5756 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5758 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5760 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5761 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5762 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5764 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5765 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5766 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5767 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5768 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5769 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5770 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5771 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5773 // Flush the pending fee update.
5774 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5775 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5776 check_added_monitors!(nodes[1], 1);
5777 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5778 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5779 check_added_monitors!(nodes[0], 2);
5781 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5782 // but now that the fee has been raised the second payment will now fail, causing us
5783 // to surface its failure to the user. The first payment should succeed.
5784 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5785 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5786 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);
5787 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 {}",
5788 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5789 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5791 // Check that the second payment failed to be sent out.
5792 let events = nodes[0].node.get_and_clear_pending_events();
5793 assert_eq!(events.len(), 2);
5795 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5796 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5797 assert_eq!(payment_hash_2.clone(), *payment_hash);
5798 assert_eq!(*payment_failed_permanently, false);
5799 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5801 _ => panic!("Unexpected event"),
5804 &Event::PaymentFailed { ref payment_hash, .. } => {
5805 assert_eq!(payment_hash_2.clone(), *payment_hash);
5807 _ => panic!("Unexpected event"),
5810 // Complete the first payment and the RAA from the fee update.
5811 let (payment_event, send_raa_event) = {
5812 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5813 assert_eq!(msgs.len(), 2);
5814 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5816 let raa = match send_raa_event {
5817 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5818 _ => panic!("Unexpected event"),
5820 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5821 check_added_monitors!(nodes[1], 1);
5822 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5823 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5824 let events = nodes[1].node.get_and_clear_pending_events();
5825 assert_eq!(events.len(), 1);
5827 Event::PendingHTLCsForwardable { .. } => {},
5828 _ => panic!("Unexpected event"),
5830 nodes[1].node.process_pending_htlc_forwards();
5831 let events = nodes[1].node.get_and_clear_pending_events();
5832 assert_eq!(events.len(), 1);
5834 Event::PaymentClaimable { .. } => {},
5835 _ => panic!("Unexpected event"),
5837 nodes[1].node.claim_funds(payment_preimage_1);
5838 check_added_monitors!(nodes[1], 1);
5839 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5841 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5842 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5843 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5844 expect_payment_sent!(nodes[0], payment_preimage_1);
5847 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5848 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5849 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5852 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5853 let chanmon_cfgs = create_chanmon_cfgs(3);
5854 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5855 // When this test was written, the default base fee floated based on the HTLC count.
5856 // It is now fixed, so we simply set the fee to the expected value here.
5857 let mut config = test_default_channel_config();
5858 config.channel_config.forwarding_fee_base_msat = 196;
5859 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5860 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5861 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5862 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5864 // First nodes[1] generates an update_fee, setting the channel's
5865 // pending_update_fee.
5867 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5868 *feerate_lock += 20;
5870 nodes[1].node.timer_tick_occurred();
5871 check_added_monitors!(nodes[1], 1);
5873 let events = nodes[1].node.get_and_clear_pending_msg_events();
5874 assert_eq!(events.len(), 1);
5875 let (update_msg, commitment_signed) = match events[0] {
5876 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5877 (update_fee.as_ref(), commitment_signed)
5879 _ => panic!("Unexpected event"),
5882 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5884 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5885 let channel_reserve = chan_stat.channel_reserve_msat;
5886 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5887 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5889 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5891 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5892 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5893 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5894 let payment_event = {
5895 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5896 check_added_monitors!(nodes[0], 1);
5898 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5899 assert_eq!(events.len(), 1);
5901 SendEvent::from_event(events.remove(0))
5903 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5904 check_added_monitors!(nodes[1], 0);
5905 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5906 expect_pending_htlcs_forwardable!(nodes[1]);
5908 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5909 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5911 // Flush the pending fee update.
5912 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5913 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5914 check_added_monitors!(nodes[2], 1);
5915 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5916 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5917 check_added_monitors!(nodes[1], 2);
5919 // A final RAA message is generated to finalize the fee update.
5920 let events = nodes[1].node.get_and_clear_pending_msg_events();
5921 assert_eq!(events.len(), 1);
5923 let raa_msg = match &events[0] {
5924 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5927 _ => panic!("Unexpected event"),
5930 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5931 check_added_monitors!(nodes[2], 1);
5932 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5934 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5935 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5936 assert_eq!(process_htlc_forwards_event.len(), 2);
5937 match &process_htlc_forwards_event[0] {
5938 &Event::PendingHTLCsForwardable { .. } => {},
5939 _ => panic!("Unexpected event"),
5942 // In response, we call ChannelManager's process_pending_htlc_forwards
5943 nodes[1].node.process_pending_htlc_forwards();
5944 check_added_monitors!(nodes[1], 1);
5946 // This causes the HTLC to be failed backwards.
5947 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5948 assert_eq!(fail_event.len(), 1);
5949 let (fail_msg, commitment_signed) = match &fail_event[0] {
5950 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5951 assert_eq!(updates.update_add_htlcs.len(), 0);
5952 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5953 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5954 assert_eq!(updates.update_fail_htlcs.len(), 1);
5955 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5957 _ => panic!("Unexpected event"),
5960 // Pass the failure messages back to nodes[0].
5961 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5962 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5964 // Complete the HTLC failure+removal process.
5965 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5966 check_added_monitors!(nodes[0], 1);
5967 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5968 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5969 check_added_monitors!(nodes[1], 2);
5970 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5971 assert_eq!(final_raa_event.len(), 1);
5972 let raa = match &final_raa_event[0] {
5973 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5974 _ => panic!("Unexpected event"),
5976 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5977 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5978 check_added_monitors!(nodes[0], 1);
5981 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5982 // 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.
5983 //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.
5986 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5987 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5988 let chanmon_cfgs = create_chanmon_cfgs(2);
5989 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5990 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5991 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5992 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5994 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5995 route.paths[0][0].fee_msat = 100;
5997 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 },
5998 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5999 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6000 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6004 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6005 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6006 let chanmon_cfgs = create_chanmon_cfgs(2);
6007 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6008 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6009 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6010 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6012 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6013 route.paths[0][0].fee_msat = 0;
6014 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 },
6015 assert_eq!(err, "Cannot send 0-msat HTLC"));
6017 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6018 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6022 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6023 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6024 let chanmon_cfgs = create_chanmon_cfgs(2);
6025 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6026 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6027 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6028 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6030 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6031 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6032 check_added_monitors!(nodes[0], 1);
6033 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6034 updates.update_add_htlcs[0].amount_msat = 0;
6036 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6037 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6038 check_closed_broadcast!(nodes[1], true).unwrap();
6039 check_added_monitors!(nodes[1], 1);
6040 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6044 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6045 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6046 //It is enforced when constructing a route.
6047 let chanmon_cfgs = create_chanmon_cfgs(2);
6048 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6049 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6050 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6051 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6053 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6054 .with_features(nodes[1].node.invoice_features());
6055 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6056 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6057 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 },
6058 assert_eq!(err, &"Channel CLTV overflowed?"));
6062 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6063 //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.
6064 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6065 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6066 let chanmon_cfgs = create_chanmon_cfgs(2);
6067 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6068 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6069 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6070 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6071 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6072 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6074 for i in 0..max_accepted_htlcs {
6075 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6076 let payment_event = {
6077 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6078 check_added_monitors!(nodes[0], 1);
6080 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6081 assert_eq!(events.len(), 1);
6082 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6083 assert_eq!(htlcs[0].htlc_id, i);
6087 SendEvent::from_event(events.remove(0))
6089 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6090 check_added_monitors!(nodes[1], 0);
6091 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6093 expect_pending_htlcs_forwardable!(nodes[1]);
6094 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6096 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6097 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 },
6098 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6100 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6101 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6105 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6106 //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.
6107 let chanmon_cfgs = create_chanmon_cfgs(2);
6108 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6109 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6110 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6111 let channel_value = 100000;
6112 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6113 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6115 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6117 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6118 // Manually create a route over our max in flight (which our router normally automatically
6120 route.paths[0][0].fee_msat = max_in_flight + 1;
6121 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 },
6122 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)));
6124 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6125 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);
6127 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6130 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6132 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6133 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6134 let chanmon_cfgs = create_chanmon_cfgs(2);
6135 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6136 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6137 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6138 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6139 let htlc_minimum_msat: u64;
6141 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6142 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6143 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6144 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6147 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6148 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6149 check_added_monitors!(nodes[0], 1);
6150 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6151 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6152 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6153 assert!(nodes[1].node.list_channels().is_empty());
6154 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6155 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()));
6156 check_added_monitors!(nodes[1], 1);
6157 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6161 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6162 //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
6163 let chanmon_cfgs = create_chanmon_cfgs(2);
6164 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6165 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6166 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6167 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6169 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6170 let channel_reserve = chan_stat.channel_reserve_msat;
6171 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6172 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6173 // The 2* and +1 are for the fee spike reserve.
6174 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6176 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6177 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6178 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6179 check_added_monitors!(nodes[0], 1);
6180 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6182 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6183 // at this time channel-initiatee receivers are not required to enforce that senders
6184 // respect the fee_spike_reserve.
6185 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6186 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6188 assert!(nodes[1].node.list_channels().is_empty());
6189 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6190 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6191 check_added_monitors!(nodes[1], 1);
6192 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6196 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6197 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6198 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6199 let chanmon_cfgs = create_chanmon_cfgs(2);
6200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6202 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6203 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6205 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6206 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6207 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6208 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6209 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6210 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6212 let mut msg = msgs::UpdateAddHTLC {
6216 payment_hash: our_payment_hash,
6217 cltv_expiry: htlc_cltv,
6218 onion_routing_packet: onion_packet.clone(),
6221 for i in 0..super::channel::OUR_MAX_HTLCS {
6222 msg.htlc_id = i as u64;
6223 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6225 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6226 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6228 assert!(nodes[1].node.list_channels().is_empty());
6229 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6230 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6231 check_added_monitors!(nodes[1], 1);
6232 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6236 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6237 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6238 let chanmon_cfgs = create_chanmon_cfgs(2);
6239 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6240 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6241 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6242 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6244 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6245 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6246 check_added_monitors!(nodes[0], 1);
6247 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6248 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;
6249 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6251 assert!(nodes[1].node.list_channels().is_empty());
6252 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6253 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6254 check_added_monitors!(nodes[1], 1);
6255 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6259 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6260 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6261 let chanmon_cfgs = create_chanmon_cfgs(2);
6262 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6263 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6264 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6266 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6267 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6268 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6269 check_added_monitors!(nodes[0], 1);
6270 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6271 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6272 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6274 assert!(nodes[1].node.list_channels().is_empty());
6275 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6276 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6277 check_added_monitors!(nodes[1], 1);
6278 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6282 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6283 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6284 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6285 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6286 let chanmon_cfgs = create_chanmon_cfgs(2);
6287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6289 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6291 create_announced_chan_between_nodes(&nodes, 0, 1);
6292 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6293 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6294 check_added_monitors!(nodes[0], 1);
6295 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6296 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6298 //Disconnect and Reconnect
6299 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6300 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6301 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();
6302 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6303 assert_eq!(reestablish_1.len(), 1);
6304 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();
6305 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6306 assert_eq!(reestablish_2.len(), 1);
6307 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6308 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6309 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6310 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6313 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6314 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6315 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6316 check_added_monitors!(nodes[1], 1);
6317 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6321 assert!(nodes[1].node.list_channels().is_empty());
6322 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6323 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6324 check_added_monitors!(nodes[1], 1);
6325 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6329 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6330 //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.
6332 let chanmon_cfgs = create_chanmon_cfgs(2);
6333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6335 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6336 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6337 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6338 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6340 check_added_monitors!(nodes[0], 1);
6341 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6342 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6344 let update_msg = msgs::UpdateFulfillHTLC{
6347 payment_preimage: our_payment_preimage,
6350 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6352 assert!(nodes[0].node.list_channels().is_empty());
6353 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6354 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()));
6355 check_added_monitors!(nodes[0], 1);
6356 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6360 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6361 //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.
6363 let chanmon_cfgs = create_chanmon_cfgs(2);
6364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6369 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6370 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6371 check_added_monitors!(nodes[0], 1);
6372 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6375 let update_msg = msgs::UpdateFailHTLC{
6378 reason: msgs::OnionErrorPacket { data: Vec::new()},
6381 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6383 assert!(nodes[0].node.list_channels().is_empty());
6384 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6385 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()));
6386 check_added_monitors!(nodes[0], 1);
6387 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6391 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6392 //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.
6394 let chanmon_cfgs = create_chanmon_cfgs(2);
6395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6397 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6398 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6400 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6401 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6402 check_added_monitors!(nodes[0], 1);
6403 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6405 let update_msg = msgs::UpdateFailMalformedHTLC{
6408 sha256_of_onion: [1; 32],
6409 failure_code: 0x8000,
6412 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6414 assert!(nodes[0].node.list_channels().is_empty());
6415 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6416 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()));
6417 check_added_monitors!(nodes[0], 1);
6418 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6422 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6423 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6425 let chanmon_cfgs = create_chanmon_cfgs(2);
6426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6428 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6429 create_announced_chan_between_nodes(&nodes, 0, 1);
6431 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6433 nodes[1].node.claim_funds(our_payment_preimage);
6434 check_added_monitors!(nodes[1], 1);
6435 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6437 let events = nodes[1].node.get_and_clear_pending_msg_events();
6438 assert_eq!(events.len(), 1);
6439 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6441 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, .. } } => {
6442 assert!(update_add_htlcs.is_empty());
6443 assert_eq!(update_fulfill_htlcs.len(), 1);
6444 assert!(update_fail_htlcs.is_empty());
6445 assert!(update_fail_malformed_htlcs.is_empty());
6446 assert!(update_fee.is_none());
6447 update_fulfill_htlcs[0].clone()
6449 _ => panic!("Unexpected event"),
6453 update_fulfill_msg.htlc_id = 1;
6455 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6457 assert!(nodes[0].node.list_channels().is_empty());
6458 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6459 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6460 check_added_monitors!(nodes[0], 1);
6461 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6465 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6466 //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.
6468 let chanmon_cfgs = create_chanmon_cfgs(2);
6469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6471 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6472 create_announced_chan_between_nodes(&nodes, 0, 1);
6474 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6476 nodes[1].node.claim_funds(our_payment_preimage);
6477 check_added_monitors!(nodes[1], 1);
6478 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6480 let events = nodes[1].node.get_and_clear_pending_msg_events();
6481 assert_eq!(events.len(), 1);
6482 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6484 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, .. } } => {
6485 assert!(update_add_htlcs.is_empty());
6486 assert_eq!(update_fulfill_htlcs.len(), 1);
6487 assert!(update_fail_htlcs.is_empty());
6488 assert!(update_fail_malformed_htlcs.is_empty());
6489 assert!(update_fee.is_none());
6490 update_fulfill_htlcs[0].clone()
6492 _ => panic!("Unexpected event"),
6496 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6498 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6500 assert!(nodes[0].node.list_channels().is_empty());
6501 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6502 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6503 check_added_monitors!(nodes[0], 1);
6504 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6508 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6509 //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.
6511 let chanmon_cfgs = create_chanmon_cfgs(2);
6512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6514 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6515 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6517 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6518 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6519 check_added_monitors!(nodes[0], 1);
6521 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6522 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6524 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6525 check_added_monitors!(nodes[1], 0);
6526 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6528 let events = nodes[1].node.get_and_clear_pending_msg_events();
6530 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6532 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, .. } } => {
6533 assert!(update_add_htlcs.is_empty());
6534 assert!(update_fulfill_htlcs.is_empty());
6535 assert!(update_fail_htlcs.is_empty());
6536 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6537 assert!(update_fee.is_none());
6538 update_fail_malformed_htlcs[0].clone()
6540 _ => panic!("Unexpected event"),
6543 update_msg.failure_code &= !0x8000;
6544 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6546 assert!(nodes[0].node.list_channels().is_empty());
6547 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6548 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6549 check_added_monitors!(nodes[0], 1);
6550 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6554 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6555 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6556 // * 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.
6558 let chanmon_cfgs = create_chanmon_cfgs(3);
6559 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6560 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6561 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6562 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6563 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6565 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6568 let mut payment_event = {
6569 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6570 check_added_monitors!(nodes[0], 1);
6571 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6572 assert_eq!(events.len(), 1);
6573 SendEvent::from_event(events.remove(0))
6575 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6576 check_added_monitors!(nodes[1], 0);
6577 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6578 expect_pending_htlcs_forwardable!(nodes[1]);
6579 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6580 assert_eq!(events_2.len(), 1);
6581 check_added_monitors!(nodes[1], 1);
6582 payment_event = SendEvent::from_event(events_2.remove(0));
6583 assert_eq!(payment_event.msgs.len(), 1);
6586 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6587 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6588 check_added_monitors!(nodes[2], 0);
6589 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6591 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6592 assert_eq!(events_3.len(), 1);
6593 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6595 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 } } => {
6596 assert!(update_add_htlcs.is_empty());
6597 assert!(update_fulfill_htlcs.is_empty());
6598 assert!(update_fail_htlcs.is_empty());
6599 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6600 assert!(update_fee.is_none());
6601 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6603 _ => panic!("Unexpected event"),
6607 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6609 check_added_monitors!(nodes[1], 0);
6610 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6611 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 }]);
6612 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6613 assert_eq!(events_4.len(), 1);
6615 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6617 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, .. } } => {
6618 assert!(update_add_htlcs.is_empty());
6619 assert!(update_fulfill_htlcs.is_empty());
6620 assert_eq!(update_fail_htlcs.len(), 1);
6621 assert!(update_fail_malformed_htlcs.is_empty());
6622 assert!(update_fee.is_none());
6624 _ => panic!("Unexpected event"),
6627 check_added_monitors!(nodes[1], 1);
6631 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6632 let chanmon_cfgs = create_chanmon_cfgs(3);
6633 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6634 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6635 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6636 create_announced_chan_between_nodes(&nodes, 0, 1);
6637 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6639 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6642 let mut payment_event = {
6643 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6644 check_added_monitors!(nodes[0], 1);
6645 SendEvent::from_node(&nodes[0])
6648 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6649 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6650 expect_pending_htlcs_forwardable!(nodes[1]);
6651 check_added_monitors!(nodes[1], 1);
6652 payment_event = SendEvent::from_node(&nodes[1]);
6653 assert_eq!(payment_event.msgs.len(), 1);
6656 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6657 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6658 check_added_monitors!(nodes[2], 0);
6659 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6661 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6662 assert_eq!(events_3.len(), 1);
6664 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6665 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6666 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6667 update_msg.failure_code |= 0x2000;
6669 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6670 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6672 _ => panic!("Unexpected event"),
6675 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6676 vec![HTLCDestination::NextHopChannel {
6677 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6678 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6679 assert_eq!(events_4.len(), 1);
6680 check_added_monitors!(nodes[1], 1);
6683 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6684 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6685 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6687 _ => panic!("Unexpected event"),
6690 let events_5 = nodes[0].node.get_and_clear_pending_events();
6691 assert_eq!(events_5.len(), 2);
6693 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6694 // the node originating the error to its next hop.
6696 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6698 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6699 assert!(is_permanent);
6700 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6702 _ => panic!("Unexpected event"),
6705 Event::PaymentFailed { payment_hash, .. } => {
6706 assert_eq!(payment_hash, our_payment_hash);
6708 _ => panic!("Unexpected event"),
6711 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6714 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6715 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6716 // 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
6717 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6719 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6720 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6723 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6724 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6726 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6727 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6729 // We route 2 dust-HTLCs between A and B
6730 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6731 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6732 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6734 // Cache one local commitment tx as previous
6735 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6737 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6738 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6739 check_added_monitors!(nodes[1], 0);
6740 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6741 check_added_monitors!(nodes[1], 1);
6743 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6744 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6745 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6746 check_added_monitors!(nodes[0], 1);
6748 // Cache one local commitment tx as lastest
6749 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6751 let events = nodes[0].node.get_and_clear_pending_msg_events();
6753 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6754 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6756 _ => panic!("Unexpected event"),
6759 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6760 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6762 _ => panic!("Unexpected event"),
6765 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6766 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6767 if announce_latest {
6768 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6770 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6773 check_closed_broadcast!(nodes[0], true);
6774 check_added_monitors!(nodes[0], 1);
6775 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6777 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6778 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6779 let events = nodes[0].node.get_and_clear_pending_events();
6780 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6781 assert_eq!(events.len(), 4);
6782 let mut first_failed = false;
6783 for event in events {
6785 Event::PaymentPathFailed { payment_hash, .. } => {
6786 if payment_hash == payment_hash_1 {
6787 assert!(!first_failed);
6788 first_failed = true;
6790 assert_eq!(payment_hash, payment_hash_2);
6793 Event::PaymentFailed { .. } => {}
6794 _ => panic!("Unexpected event"),
6800 fn test_failure_delay_dust_htlc_local_commitment() {
6801 do_test_failure_delay_dust_htlc_local_commitment(true);
6802 do_test_failure_delay_dust_htlc_local_commitment(false);
6805 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6806 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6807 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6808 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6809 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6810 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6811 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6813 let chanmon_cfgs = create_chanmon_cfgs(3);
6814 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6815 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6816 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6817 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6819 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6820 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6822 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6823 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6825 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6826 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6828 // We revoked bs_commitment_tx
6830 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6831 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6834 let mut timeout_tx = Vec::new();
6836 // We fail dust-HTLC 1 by broadcast of local commitment tx
6837 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6838 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6839 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6840 expect_payment_failed!(nodes[0], dust_hash, false);
6842 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6843 check_closed_broadcast!(nodes[0], true);
6844 check_added_monitors!(nodes[0], 1);
6845 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6846 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6847 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6848 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6849 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6850 mine_transaction(&nodes[0], &timeout_tx[0]);
6851 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6852 expect_payment_failed!(nodes[0], non_dust_hash, false);
6854 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6855 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6856 check_closed_broadcast!(nodes[0], true);
6857 check_added_monitors!(nodes[0], 1);
6858 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6859 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6861 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6862 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6863 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6864 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6865 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6866 // dust HTLC should have been failed.
6867 expect_payment_failed!(nodes[0], dust_hash, false);
6870 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6872 assert_eq!(timeout_tx[0].lock_time.0, 12);
6874 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6875 mine_transaction(&nodes[0], &timeout_tx[0]);
6876 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6877 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6878 expect_payment_failed!(nodes[0], non_dust_hash, false);
6883 fn test_sweep_outbound_htlc_failure_update() {
6884 do_test_sweep_outbound_htlc_failure_update(false, true);
6885 do_test_sweep_outbound_htlc_failure_update(false, false);
6886 do_test_sweep_outbound_htlc_failure_update(true, false);
6890 fn test_user_configurable_csv_delay() {
6891 // We test our channel constructors yield errors when we pass them absurd csv delay
6893 let mut low_our_to_self_config = UserConfig::default();
6894 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6895 let mut high_their_to_self_config = UserConfig::default();
6896 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6897 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6898 let chanmon_cfgs = create_chanmon_cfgs(2);
6899 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6900 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6901 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6903 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6904 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6905 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6906 &low_our_to_self_config, 0, 42)
6909 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())); },
6910 _ => panic!("Unexpected event"),
6912 } else { assert!(false) }
6914 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6915 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6916 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6917 open_channel.to_self_delay = 200;
6918 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6919 &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,
6920 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6923 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())); },
6924 _ => panic!("Unexpected event"),
6926 } else { assert!(false); }
6928 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6929 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6930 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()));
6931 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6932 accept_channel.to_self_delay = 200;
6933 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6935 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6937 &ErrorAction::SendErrorMessage { ref msg } => {
6938 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()));
6939 reason_msg = msg.data.clone();
6943 } else { panic!(); }
6944 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6946 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6947 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6948 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6949 open_channel.to_self_delay = 200;
6950 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6951 &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,
6952 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6955 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())); },
6956 _ => panic!("Unexpected event"),
6958 } else { assert!(false); }
6962 fn test_check_htlc_underpaying() {
6963 // Send payment through A -> B but A is maliciously
6964 // sending a probe payment (i.e less than expected value0
6965 // to B, B should refuse payment.
6967 let chanmon_cfgs = create_chanmon_cfgs(2);
6968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6970 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6972 // Create some initial channels
6973 create_announced_chan_between_nodes(&nodes, 0, 1);
6975 let scorer = test_utils::TestScorer::new();
6976 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6977 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6978 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();
6979 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6980 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6981 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6982 check_added_monitors!(nodes[0], 1);
6984 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6985 assert_eq!(events.len(), 1);
6986 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6987 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6988 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6990 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6991 // and then will wait a second random delay before failing the HTLC back:
6992 expect_pending_htlcs_forwardable!(nodes[1]);
6993 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6995 // Node 3 is expecting payment of 100_000 but received 10_000,
6996 // it should fail htlc like we didn't know the preimage.
6997 nodes[1].node.process_pending_htlc_forwards();
6999 let events = nodes[1].node.get_and_clear_pending_msg_events();
7000 assert_eq!(events.len(), 1);
7001 let (update_fail_htlc, commitment_signed) = match events[0] {
7002 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 } } => {
7003 assert!(update_add_htlcs.is_empty());
7004 assert!(update_fulfill_htlcs.is_empty());
7005 assert_eq!(update_fail_htlcs.len(), 1);
7006 assert!(update_fail_malformed_htlcs.is_empty());
7007 assert!(update_fee.is_none());
7008 (update_fail_htlcs[0].clone(), commitment_signed)
7010 _ => panic!("Unexpected event"),
7012 check_added_monitors!(nodes[1], 1);
7014 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7015 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7017 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7018 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7019 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7020 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7024 fn test_announce_disable_channels() {
7025 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7026 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7028 let chanmon_cfgs = create_chanmon_cfgs(2);
7029 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7030 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7031 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7033 create_announced_chan_between_nodes(&nodes, 0, 1);
7034 create_announced_chan_between_nodes(&nodes, 1, 0);
7035 create_announced_chan_between_nodes(&nodes, 0, 1);
7038 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7039 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7041 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7042 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7043 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7044 assert_eq!(msg_events.len(), 3);
7045 let mut chans_disabled = HashMap::new();
7046 for e in msg_events {
7048 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7049 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7050 // Check that each channel gets updated exactly once
7051 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7052 panic!("Generated ChannelUpdate for wrong chan!");
7055 _ => panic!("Unexpected event"),
7059 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();
7060 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7061 assert_eq!(reestablish_1.len(), 3);
7062 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();
7063 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7064 assert_eq!(reestablish_2.len(), 3);
7066 // Reestablish chan_1
7067 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7068 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7069 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7070 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7071 // Reestablish chan_2
7072 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7073 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7074 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7075 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7076 // Reestablish chan_3
7077 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7078 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7079 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7080 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7082 nodes[0].node.timer_tick_occurred();
7083 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7084 nodes[0].node.timer_tick_occurred();
7085 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7086 assert_eq!(msg_events.len(), 3);
7087 for e in msg_events {
7089 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7090 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7091 match chans_disabled.remove(&msg.contents.short_channel_id) {
7092 // Each update should have a higher timestamp than the previous one, replacing
7094 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7095 None => panic!("Generated ChannelUpdate for wrong chan!"),
7098 _ => panic!("Unexpected event"),
7101 // Check that each channel gets updated exactly once
7102 assert!(chans_disabled.is_empty());
7106 fn test_bump_penalty_txn_on_revoked_commitment() {
7107 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7108 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7110 let chanmon_cfgs = create_chanmon_cfgs(2);
7111 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7112 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7113 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7115 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7117 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7118 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7119 .with_features(nodes[0].node.invoice_features());
7120 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7121 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7123 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7124 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7125 assert_eq!(revoked_txn[0].output.len(), 4);
7126 assert_eq!(revoked_txn[0].input.len(), 1);
7127 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7128 let revoked_txid = revoked_txn[0].txid();
7130 let mut penalty_sum = 0;
7131 for outp in revoked_txn[0].output.iter() {
7132 if outp.script_pubkey.is_v0_p2wsh() {
7133 penalty_sum += outp.value;
7137 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7138 let header_114 = connect_blocks(&nodes[1], 14);
7140 // Actually revoke tx by claiming a HTLC
7141 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7142 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7143 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7144 check_added_monitors!(nodes[1], 1);
7146 // One or more justice tx should have been broadcast, check it
7150 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7151 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7152 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7153 assert_eq!(node_txn[0].output.len(), 1);
7154 check_spends!(node_txn[0], revoked_txn[0]);
7155 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7156 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7157 penalty_1 = node_txn[0].txid();
7161 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7162 connect_blocks(&nodes[1], 15);
7163 let mut penalty_2 = penalty_1;
7164 let mut feerate_2 = 0;
7166 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7167 assert_eq!(node_txn.len(), 1);
7168 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7169 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7170 assert_eq!(node_txn[0].output.len(), 1);
7171 check_spends!(node_txn[0], revoked_txn[0]);
7172 penalty_2 = node_txn[0].txid();
7173 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7174 assert_ne!(penalty_2, penalty_1);
7175 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7176 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7177 // Verify 25% bump heuristic
7178 assert!(feerate_2 * 100 >= feerate_1 * 125);
7182 assert_ne!(feerate_2, 0);
7184 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7185 connect_blocks(&nodes[1], 1);
7187 let mut feerate_3 = 0;
7189 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7190 assert_eq!(node_txn.len(), 1);
7191 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7192 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7193 assert_eq!(node_txn[0].output.len(), 1);
7194 check_spends!(node_txn[0], revoked_txn[0]);
7195 penalty_3 = node_txn[0].txid();
7196 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7197 assert_ne!(penalty_3, penalty_2);
7198 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7199 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7200 // Verify 25% bump heuristic
7201 assert!(feerate_3 * 100 >= feerate_2 * 125);
7205 assert_ne!(feerate_3, 0);
7207 nodes[1].node.get_and_clear_pending_events();
7208 nodes[1].node.get_and_clear_pending_msg_events();
7212 fn test_bump_penalty_txn_on_revoked_htlcs() {
7213 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7214 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7216 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7217 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7218 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7219 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7220 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7222 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7223 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7224 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7225 let scorer = test_utils::TestScorer::new();
7226 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7227 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7228 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7229 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7230 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7231 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7232 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7233 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7235 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7236 assert_eq!(revoked_local_txn[0].input.len(), 1);
7237 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7239 // Revoke local commitment tx
7240 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7242 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7243 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7244 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7245 check_closed_broadcast!(nodes[1], true);
7246 check_added_monitors!(nodes[1], 1);
7247 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7248 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7250 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7251 assert_eq!(revoked_htlc_txn.len(), 2);
7253 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7254 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7255 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7257 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7258 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7259 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7260 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7262 // Broadcast set of revoked txn on A
7263 let hash_128 = connect_blocks(&nodes[0], 40);
7264 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7265 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7266 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7267 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7268 let events = nodes[0].node.get_and_clear_pending_events();
7269 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7270 match events.last().unwrap() {
7271 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7272 _ => panic!("Unexpected event"),
7278 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7279 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7280 // Verify claim tx are spending revoked HTLC txn
7282 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7283 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7284 // which are included in the same block (they are broadcasted because we scan the
7285 // transactions linearly and generate claims as we go, they likely should be removed in the
7287 assert_eq!(node_txn[0].input.len(), 1);
7288 check_spends!(node_txn[0], revoked_local_txn[0]);
7289 assert_eq!(node_txn[1].input.len(), 1);
7290 check_spends!(node_txn[1], revoked_local_txn[0]);
7291 assert_eq!(node_txn[2].input.len(), 1);
7292 check_spends!(node_txn[2], revoked_local_txn[0]);
7294 // Each of the three justice transactions claim a separate (single) output of the three
7295 // available, which we check here:
7296 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7297 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7298 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7300 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7301 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7303 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7304 // output, checked above).
7305 assert_eq!(node_txn[3].input.len(), 2);
7306 assert_eq!(node_txn[3].output.len(), 1);
7307 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7309 first = node_txn[3].txid();
7310 // Store both feerates for later comparison
7311 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7312 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7313 penalty_txn = vec![node_txn[2].clone()];
7317 // Connect one more block to see if bumped penalty are issued for HTLC txn
7318 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7319 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7320 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7321 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7323 // Few more blocks to confirm penalty txn
7324 connect_blocks(&nodes[0], 4);
7325 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7326 let header_144 = connect_blocks(&nodes[0], 9);
7328 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7329 assert_eq!(node_txn.len(), 1);
7331 assert_eq!(node_txn[0].input.len(), 2);
7332 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7333 // Verify bumped tx is different and 25% bump heuristic
7334 assert_ne!(first, node_txn[0].txid());
7335 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7336 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7337 assert!(feerate_2 * 100 > feerate_1 * 125);
7338 let txn = vec![node_txn[0].clone()];
7342 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7343 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7344 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7345 connect_blocks(&nodes[0], 20);
7347 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7348 // We verify than no new transaction has been broadcast because previously
7349 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7350 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7351 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7352 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7353 // up bumped justice generation.
7354 assert_eq!(node_txn.len(), 0);
7357 check_closed_broadcast!(nodes[0], true);
7358 check_added_monitors!(nodes[0], 1);
7362 fn test_bump_penalty_txn_on_remote_commitment() {
7363 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7364 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7367 // Provide preimage for one
7368 // Check aggregation
7370 let chanmon_cfgs = create_chanmon_cfgs(2);
7371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7373 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7375 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7376 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7377 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7379 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7380 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7381 assert_eq!(remote_txn[0].output.len(), 4);
7382 assert_eq!(remote_txn[0].input.len(), 1);
7383 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7385 // Claim a HTLC without revocation (provide B monitor with preimage)
7386 nodes[1].node.claim_funds(payment_preimage);
7387 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7388 mine_transaction(&nodes[1], &remote_txn[0]);
7389 check_added_monitors!(nodes[1], 2);
7390 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7392 // One or more claim tx should have been broadcast, check it
7396 let feerate_timeout;
7397 let feerate_preimage;
7399 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7400 // 3 transactions including:
7401 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7402 assert_eq!(node_txn.len(), 3);
7403 assert_eq!(node_txn[0].input.len(), 1);
7404 assert_eq!(node_txn[1].input.len(), 1);
7405 assert_eq!(node_txn[2].input.len(), 1);
7406 check_spends!(node_txn[0], remote_txn[0]);
7407 check_spends!(node_txn[1], remote_txn[0]);
7408 check_spends!(node_txn[2], remote_txn[0]);
7410 preimage = node_txn[0].txid();
7411 let index = node_txn[0].input[0].previous_output.vout;
7412 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7413 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7415 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7416 (node_txn[2].clone(), node_txn[1].clone())
7418 (node_txn[1].clone(), node_txn[2].clone())
7421 preimage_bump = preimage_bump_tx;
7422 check_spends!(preimage_bump, remote_txn[0]);
7423 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7425 timeout = timeout_tx.txid();
7426 let index = timeout_tx.input[0].previous_output.vout;
7427 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7428 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7432 assert_ne!(feerate_timeout, 0);
7433 assert_ne!(feerate_preimage, 0);
7435 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7436 connect_blocks(&nodes[1], 15);
7438 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7439 assert_eq!(node_txn.len(), 1);
7440 assert_eq!(node_txn[0].input.len(), 1);
7441 assert_eq!(preimage_bump.input.len(), 1);
7442 check_spends!(node_txn[0], remote_txn[0]);
7443 check_spends!(preimage_bump, remote_txn[0]);
7445 let index = preimage_bump.input[0].previous_output.vout;
7446 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7447 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7448 assert!(new_feerate * 100 > feerate_timeout * 125);
7449 assert_ne!(timeout, preimage_bump.txid());
7451 let index = node_txn[0].input[0].previous_output.vout;
7452 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7453 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7454 assert!(new_feerate * 100 > feerate_preimage * 125);
7455 assert_ne!(preimage, node_txn[0].txid());
7460 nodes[1].node.get_and_clear_pending_events();
7461 nodes[1].node.get_and_clear_pending_msg_events();
7465 fn test_counterparty_raa_skip_no_crash() {
7466 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7467 // commitment transaction, we would have happily carried on and provided them the next
7468 // commitment transaction based on one RAA forward. This would probably eventually have led to
7469 // channel closure, but it would not have resulted in funds loss. Still, our
7470 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7471 // check simply that the channel is closed in response to such an RAA, but don't check whether
7472 // we decide to punish our counterparty for revoking their funds (as we don't currently
7474 let chanmon_cfgs = create_chanmon_cfgs(2);
7475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7477 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7478 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7480 let per_commitment_secret;
7481 let next_per_commitment_point;
7483 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7484 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7485 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7487 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7489 // Make signer believe we got a counterparty signature, so that it allows the revocation
7490 keys.get_enforcement_state().last_holder_commitment -= 1;
7491 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7493 // Must revoke without gaps
7494 keys.get_enforcement_state().last_holder_commitment -= 1;
7495 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7497 keys.get_enforcement_state().last_holder_commitment -= 1;
7498 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7499 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7502 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7503 &msgs::RevokeAndACK {
7505 per_commitment_secret,
7506 next_per_commitment_point,
7508 next_local_nonce: None,
7510 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7511 check_added_monitors!(nodes[1], 1);
7512 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7516 fn test_bump_txn_sanitize_tracking_maps() {
7517 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7518 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7520 let chanmon_cfgs = create_chanmon_cfgs(2);
7521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7523 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7525 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7526 // Lock HTLC in both directions
7527 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7528 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7530 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7531 assert_eq!(revoked_local_txn[0].input.len(), 1);
7532 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7534 // Revoke local commitment tx
7535 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7537 // Broadcast set of revoked txn on A
7538 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7539 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7540 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7542 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7543 check_closed_broadcast!(nodes[0], true);
7544 check_added_monitors!(nodes[0], 1);
7545 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7547 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7548 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7549 check_spends!(node_txn[0], revoked_local_txn[0]);
7550 check_spends!(node_txn[1], revoked_local_txn[0]);
7551 check_spends!(node_txn[2], revoked_local_txn[0]);
7552 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7556 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7557 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7558 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7560 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7561 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7562 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7567 fn test_pending_claimed_htlc_no_balance_underflow() {
7568 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7569 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7570 let chanmon_cfgs = create_chanmon_cfgs(2);
7571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7574 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7576 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7577 nodes[1].node.claim_funds(payment_preimage);
7578 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7579 check_added_monitors!(nodes[1], 1);
7580 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7582 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7583 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7584 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7585 check_added_monitors!(nodes[0], 1);
7586 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7588 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7589 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7590 // can get our balance.
7592 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7593 // the public key of the only hop. This works around ChannelDetails not showing the
7594 // almost-claimed HTLC as available balance.
7595 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7596 route.payment_params = None; // This is all wrong, but unnecessary
7597 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7598 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7599 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7601 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7605 fn test_channel_conf_timeout() {
7606 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7607 // confirm within 2016 blocks, as recommended by BOLT 2.
7608 let chanmon_cfgs = create_chanmon_cfgs(2);
7609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7613 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7615 // The outbound node should wait forever for confirmation:
7616 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7617 // copied here instead of directly referencing the constant.
7618 connect_blocks(&nodes[0], 2016);
7619 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7621 // The inbound node should fail the channel after exactly 2016 blocks
7622 connect_blocks(&nodes[1], 2015);
7623 check_added_monitors!(nodes[1], 0);
7624 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7626 connect_blocks(&nodes[1], 1);
7627 check_added_monitors!(nodes[1], 1);
7628 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7629 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7630 assert_eq!(close_ev.len(), 1);
7632 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7633 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7634 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7636 _ => panic!("Unexpected event"),
7641 fn test_override_channel_config() {
7642 let chanmon_cfgs = create_chanmon_cfgs(2);
7643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7645 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7647 // Node0 initiates a channel to node1 using the override config.
7648 let mut override_config = UserConfig::default();
7649 override_config.channel_handshake_config.our_to_self_delay = 200;
7651 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7653 // Assert the channel created by node0 is using the override config.
7654 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7655 assert_eq!(res.channel_flags, 0);
7656 assert_eq!(res.to_self_delay, 200);
7660 fn test_override_0msat_htlc_minimum() {
7661 let mut zero_config = UserConfig::default();
7662 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7663 let chanmon_cfgs = create_chanmon_cfgs(2);
7664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7666 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7668 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7669 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7670 assert_eq!(res.htlc_minimum_msat, 1);
7672 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7673 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7674 assert_eq!(res.htlc_minimum_msat, 1);
7678 fn test_channel_update_has_correct_htlc_maximum_msat() {
7679 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7680 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7681 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7682 // 90% of the `channel_value`.
7683 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7685 let mut config_30_percent = UserConfig::default();
7686 config_30_percent.channel_handshake_config.announced_channel = true;
7687 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7688 let mut config_50_percent = UserConfig::default();
7689 config_50_percent.channel_handshake_config.announced_channel = true;
7690 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7691 let mut config_95_percent = UserConfig::default();
7692 config_95_percent.channel_handshake_config.announced_channel = true;
7693 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7694 let mut config_100_percent = UserConfig::default();
7695 config_100_percent.channel_handshake_config.announced_channel = true;
7696 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7698 let chanmon_cfgs = create_chanmon_cfgs(4);
7699 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7700 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)]);
7701 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7703 let channel_value_satoshis = 100000;
7704 let channel_value_msat = channel_value_satoshis * 1000;
7705 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7706 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7707 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7709 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7710 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7712 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7713 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7714 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7715 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7716 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7717 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7719 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7720 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7722 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7723 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7724 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7726 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7730 fn test_manually_accept_inbound_channel_request() {
7731 let mut manually_accept_conf = UserConfig::default();
7732 manually_accept_conf.manually_accept_inbound_channels = true;
7733 let chanmon_cfgs = create_chanmon_cfgs(2);
7734 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7735 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7736 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7738 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7739 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7741 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7743 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7744 // accepting the inbound channel request.
7745 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7747 let events = nodes[1].node.get_and_clear_pending_events();
7749 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7750 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7752 _ => panic!("Unexpected event"),
7755 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7756 assert_eq!(accept_msg_ev.len(), 1);
7758 match accept_msg_ev[0] {
7759 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7760 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7762 _ => panic!("Unexpected event"),
7765 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7767 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7768 assert_eq!(close_msg_ev.len(), 1);
7770 let events = nodes[1].node.get_and_clear_pending_events();
7772 Event::ChannelClosed { user_channel_id, .. } => {
7773 assert_eq!(user_channel_id, 23);
7775 _ => panic!("Unexpected event"),
7780 fn test_manually_reject_inbound_channel_request() {
7781 let mut manually_accept_conf = UserConfig::default();
7782 manually_accept_conf.manually_accept_inbound_channels = true;
7783 let chanmon_cfgs = create_chanmon_cfgs(2);
7784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7788 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7789 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7791 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7793 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7794 // rejecting the inbound channel request.
7795 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7797 let events = nodes[1].node.get_and_clear_pending_events();
7799 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7800 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7802 _ => panic!("Unexpected event"),
7805 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7806 assert_eq!(close_msg_ev.len(), 1);
7808 match close_msg_ev[0] {
7809 MessageSendEvent::HandleError { ref node_id, .. } => {
7810 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7812 _ => panic!("Unexpected event"),
7814 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7818 fn test_reject_funding_before_inbound_channel_accepted() {
7819 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7820 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7821 // the node operator before the counterparty sends a `FundingCreated` message. If a
7822 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7823 // and the channel should be closed.
7824 let mut manually_accept_conf = UserConfig::default();
7825 manually_accept_conf.manually_accept_inbound_channels = true;
7826 let chanmon_cfgs = create_chanmon_cfgs(2);
7827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7829 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7831 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7832 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7833 let temp_channel_id = res.temporary_channel_id;
7835 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7837 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7838 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7840 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7841 nodes[1].node.get_and_clear_pending_events();
7843 // Get the `AcceptChannel` message of `nodes[1]` without calling
7844 // `ChannelManager::accept_inbound_channel`, which generates a
7845 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7846 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7847 // succeed when `nodes[0]` is passed to it.
7848 let accept_chan_msg = {
7849 let mut node_1_per_peer_lock;
7850 let mut node_1_peer_state_lock;
7851 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7852 channel.get_accept_channel_message()
7854 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7856 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7858 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7859 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7861 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7862 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7864 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7865 assert_eq!(close_msg_ev.len(), 1);
7867 let expected_err = "FundingCreated message received before the channel was accepted";
7868 match close_msg_ev[0] {
7869 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7870 assert_eq!(msg.channel_id, temp_channel_id);
7871 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7872 assert_eq!(msg.data, expected_err);
7874 _ => panic!("Unexpected event"),
7877 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7881 fn test_can_not_accept_inbound_channel_twice() {
7882 let mut manually_accept_conf = UserConfig::default();
7883 manually_accept_conf.manually_accept_inbound_channels = true;
7884 let chanmon_cfgs = create_chanmon_cfgs(2);
7885 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7886 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7887 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7889 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7890 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7892 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7894 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7895 // accepting the inbound channel request.
7896 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7898 let events = nodes[1].node.get_and_clear_pending_events();
7900 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7901 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7902 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7904 Err(APIError::APIMisuseError { err }) => {
7905 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7907 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7908 Err(_) => panic!("Unexpected Error"),
7911 _ => panic!("Unexpected event"),
7914 // Ensure that the channel wasn't closed after attempting to accept it twice.
7915 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7916 assert_eq!(accept_msg_ev.len(), 1);
7918 match accept_msg_ev[0] {
7919 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7920 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7922 _ => panic!("Unexpected event"),
7927 fn test_can_not_accept_unknown_inbound_channel() {
7928 let chanmon_cfg = create_chanmon_cfgs(2);
7929 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7930 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7931 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7933 let unknown_channel_id = [0; 32];
7934 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7936 Err(APIError::ChannelUnavailable { err }) => {
7937 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()));
7939 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7940 Err(_) => panic!("Unexpected Error"),
7945 fn test_onion_value_mpp_set_calculation() {
7946 // Test that we use the onion value `amt_to_forward` when
7947 // calculating whether we've reached the `total_msat` of an MPP
7948 // by having a routing node forward more than `amt_to_forward`
7949 // and checking that the receiving node doesn't generate
7950 // a PaymentClaimable event too early
7952 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7953 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7954 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7955 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7957 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7958 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7959 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7960 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7962 let total_msat = 100_000;
7963 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7964 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7965 let sample_path = route.paths.pop().unwrap();
7967 let mut path_1 = sample_path.clone();
7968 path_1[0].pubkey = nodes[1].node.get_our_node_id();
7969 path_1[0].short_channel_id = chan_1_id;
7970 path_1[1].pubkey = nodes[3].node.get_our_node_id();
7971 path_1[1].short_channel_id = chan_3_id;
7972 path_1[1].fee_msat = 100_000;
7973 route.paths.push(path_1);
7975 let mut path_2 = sample_path.clone();
7976 path_2[0].pubkey = nodes[2].node.get_our_node_id();
7977 path_2[0].short_channel_id = chan_2_id;
7978 path_2[1].pubkey = nodes[3].node.get_our_node_id();
7979 path_2[1].short_channel_id = chan_4_id;
7980 path_2[1].fee_msat = 1_000;
7981 route.paths.push(path_2);
7984 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7985 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
7986 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();
7987 check_added_monitors!(nodes[0], expected_paths.len());
7989 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7990 assert_eq!(events.len(), expected_paths.len());
7993 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
7994 let mut payment_event = SendEvent::from_event(ev);
7995 let mut prev_node = &nodes[0];
7997 for (idx, &node) in expected_paths[0].iter().enumerate() {
7998 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8000 if idx == 0 { // routing node
8001 let session_priv = [3; 32];
8002 let height = nodes[0].best_block_info().1;
8003 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8004 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8005 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000, &Some(our_payment_secret), height + 1, &None).unwrap();
8006 // Edit amt_to_forward to simulate the sender having set
8007 // the final amount and the routing node taking less fee
8008 onion_payloads[1].amt_to_forward = 99_000;
8009 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8010 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8013 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8014 check_added_monitors!(node, 0);
8015 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8016 expect_pending_htlcs_forwardable!(node);
8019 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8020 assert_eq!(events_2.len(), 1);
8021 check_added_monitors!(node, 1);
8022 payment_event = SendEvent::from_event(events_2.remove(0));
8023 assert_eq!(payment_event.msgs.len(), 1);
8025 let events_2 = node.node.get_and_clear_pending_events();
8026 assert!(events_2.is_empty());
8033 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8034 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8036 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8039 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8041 let routing_node_count = msat_amounts.len();
8042 let node_count = routing_node_count + 2;
8044 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8045 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8046 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8047 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8052 // Create channels for each amount
8053 let mut expected_paths = Vec::with_capacity(routing_node_count);
8054 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8055 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8056 for i in 0..routing_node_count {
8057 let routing_node = 2 + i;
8058 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8059 src_chan_ids.push(src_chan_id);
8060 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8061 dst_chan_ids.push(dst_chan_id);
8062 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8063 expected_paths.push(path);
8065 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8067 // Create a route for each amount
8068 let example_amount = 100000;
8069 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);
8070 let sample_path = route.paths.pop().unwrap();
8071 for i in 0..routing_node_count {
8072 let routing_node = 2 + i;
8073 let mut path = sample_path.clone();
8074 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8075 path[0].short_channel_id = src_chan_ids[i];
8076 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8077 path[1].short_channel_id = dst_chan_ids[i];
8078 path[1].fee_msat = msat_amounts[i];
8079 route.paths.push(path);
8082 // Send payment with manually set total_msat
8083 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8084 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &route).unwrap();
8085 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();
8086 check_added_monitors!(nodes[src_idx], expected_paths.len());
8088 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8089 assert_eq!(events.len(), expected_paths.len());
8090 let mut amount_received = 0;
8091 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8092 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8094 let current_path_amount = msat_amounts[path_idx];
8095 amount_received += current_path_amount;
8096 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8097 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8100 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8104 fn test_overshoot_mpp() {
8105 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8106 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8110 fn test_simple_mpp() {
8111 // Simple test of sending a multi-path payment.
8112 let chanmon_cfgs = create_chanmon_cfgs(4);
8113 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8114 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8115 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8117 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8118 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8119 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8120 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8122 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8123 let path = route.paths[0].clone();
8124 route.paths.push(path);
8125 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8126 route.paths[0][0].short_channel_id = chan_1_id;
8127 route.paths[0][1].short_channel_id = chan_3_id;
8128 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8129 route.paths[1][0].short_channel_id = chan_2_id;
8130 route.paths[1][1].short_channel_id = chan_4_id;
8131 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8132 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8136 fn test_preimage_storage() {
8137 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8138 let chanmon_cfgs = create_chanmon_cfgs(2);
8139 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8140 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8141 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8143 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8146 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8147 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8148 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8149 check_added_monitors!(nodes[0], 1);
8150 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8151 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8152 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8153 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8155 // Note that after leaving the above scope we have no knowledge of any arguments or return
8156 // values from previous calls.
8157 expect_pending_htlcs_forwardable!(nodes[1]);
8158 let events = nodes[1].node.get_and_clear_pending_events();
8159 assert_eq!(events.len(), 1);
8161 Event::PaymentClaimable { ref purpose, .. } => {
8163 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8164 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8166 _ => panic!("expected PaymentPurpose::InvoicePayment")
8169 _ => panic!("Unexpected event"),
8174 #[allow(deprecated)]
8175 fn test_secret_timeout() {
8176 // Simple test of payment secret storage time outs. After
8177 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8178 let chanmon_cfgs = create_chanmon_cfgs(2);
8179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8181 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8183 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8185 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8187 // We should fail to register the same payment hash twice, at least until we've connected a
8188 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8189 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8190 assert_eq!(err, "Duplicate payment hash");
8191 } else { panic!(); }
8193 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8195 header: BlockHeader {
8197 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8198 merkle_root: TxMerkleNode::all_zeros(),
8199 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8203 connect_block(&nodes[1], &block);
8204 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8205 assert_eq!(err, "Duplicate payment hash");
8206 } else { panic!(); }
8208 // If we then connect the second block, we should be able to register the same payment hash
8209 // again (this time getting a new payment secret).
8210 block.header.prev_blockhash = block.header.block_hash();
8211 block.header.time += 1;
8212 connect_block(&nodes[1], &block);
8213 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8214 assert_ne!(payment_secret_1, our_payment_secret);
8217 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8218 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8219 check_added_monitors!(nodes[0], 1);
8220 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8221 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8222 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8223 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8225 // Note that after leaving the above scope we have no knowledge of any arguments or return
8226 // values from previous calls.
8227 expect_pending_htlcs_forwardable!(nodes[1]);
8228 let events = nodes[1].node.get_and_clear_pending_events();
8229 assert_eq!(events.len(), 1);
8231 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8232 assert!(payment_preimage.is_none());
8233 assert_eq!(payment_secret, our_payment_secret);
8234 // We don't actually have the payment preimage with which to claim this payment!
8236 _ => panic!("Unexpected event"),
8241 fn test_bad_secret_hash() {
8242 // Simple test of unregistered payment hash/invalid payment secret handling
8243 let chanmon_cfgs = create_chanmon_cfgs(2);
8244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8246 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8248 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8250 let random_payment_hash = PaymentHash([42; 32]);
8251 let random_payment_secret = PaymentSecret([43; 32]);
8252 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8253 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8255 // All the below cases should end up being handled exactly identically, so we macro the
8256 // resulting events.
8257 macro_rules! handle_unknown_invalid_payment_data {
8258 ($payment_hash: expr) => {
8259 check_added_monitors!(nodes[0], 1);
8260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8261 let payment_event = SendEvent::from_event(events.pop().unwrap());
8262 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8263 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8265 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8266 // again to process the pending backwards-failure of the HTLC
8267 expect_pending_htlcs_forwardable!(nodes[1]);
8268 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8269 check_added_monitors!(nodes[1], 1);
8271 // We should fail the payment back
8272 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8273 match events.pop().unwrap() {
8274 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8275 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8276 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8278 _ => panic!("Unexpected event"),
8283 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8284 // Error data is the HTLC value (100,000) and current block height
8285 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8287 // Send a payment with the right payment hash but the wrong payment secret
8288 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8289 handle_unknown_invalid_payment_data!(our_payment_hash);
8290 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8292 // Send a payment with a random payment hash, but the right payment secret
8293 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8294 handle_unknown_invalid_payment_data!(random_payment_hash);
8295 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8297 // Send a payment with a random payment hash and random payment secret
8298 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8299 handle_unknown_invalid_payment_data!(random_payment_hash);
8300 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8304 fn test_update_err_monitor_lockdown() {
8305 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8306 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8307 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8310 // This scenario may happen in a watchtower setup, where watchtower process a block height
8311 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8312 // commitment at same time.
8314 let chanmon_cfgs = create_chanmon_cfgs(2);
8315 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8316 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8317 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8319 // Create some initial channel
8320 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8321 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8323 // Rebalance the network to generate htlc in the two directions
8324 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8326 // Route a HTLC from node 0 to node 1 (but don't settle)
8327 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8329 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8330 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8331 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8332 let persister = test_utils::TestPersister::new();
8335 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8336 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8337 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8338 assert!(new_monitor == *monitor);
8341 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);
8342 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8345 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8346 let block = Block { header, txdata: vec![] };
8347 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8348 // transaction lock time requirements here.
8349 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8350 watchtower.chain_monitor.block_connected(&block, 200);
8352 // Try to update ChannelMonitor
8353 nodes[1].node.claim_funds(preimage);
8354 check_added_monitors!(nodes[1], 1);
8355 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8357 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8358 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8359 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8361 let mut node_0_per_peer_lock;
8362 let mut node_0_peer_state_lock;
8363 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8364 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8365 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8366 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8367 } else { assert!(false); }
8369 // Our local monitor is in-sync and hasn't processed yet timeout
8370 check_added_monitors!(nodes[0], 1);
8371 let events = nodes[0].node.get_and_clear_pending_events();
8372 assert_eq!(events.len(), 1);
8376 fn test_concurrent_monitor_claim() {
8377 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8378 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8379 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8380 // state N+1 confirms. Alice claims output from state N+1.
8382 let chanmon_cfgs = create_chanmon_cfgs(2);
8383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8385 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8387 // Create some initial channel
8388 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8389 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8391 // Rebalance the network to generate htlc in the two directions
8392 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8394 // Route a HTLC from node 0 to node 1 (but don't settle)
8395 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8397 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8398 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8399 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8400 let persister = test_utils::TestPersister::new();
8401 let watchtower_alice = {
8403 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8404 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8405 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8406 assert!(new_monitor == *monitor);
8409 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);
8410 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8413 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8414 let block = Block { header, txdata: vec![] };
8415 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8416 // transaction lock time requirements here.
8417 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));
8418 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8420 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8422 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8423 assert_eq!(txn.len(), 2);
8427 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8428 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8429 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8430 let persister = test_utils::TestPersister::new();
8431 let watchtower_bob = {
8433 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8434 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8435 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8436 assert!(new_monitor == *monitor);
8439 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);
8440 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8443 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8444 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8446 // Route another payment to generate another update with still previous HTLC pending
8447 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8449 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8451 check_added_monitors!(nodes[1], 1);
8453 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8454 assert_eq!(updates.update_add_htlcs.len(), 1);
8455 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8457 let mut node_0_per_peer_lock;
8458 let mut node_0_peer_state_lock;
8459 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8460 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8461 // Watchtower Alice should already have seen the block and reject the update
8462 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8463 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8464 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8465 } else { assert!(false); }
8467 // Our local monitor is in-sync and hasn't processed yet timeout
8468 check_added_monitors!(nodes[0], 1);
8470 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8471 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8472 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8474 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8477 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8478 assert_eq!(txn.len(), 2);
8479 bob_state_y = txn[0].clone();
8483 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8484 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8485 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);
8487 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8488 assert_eq!(htlc_txn.len(), 1);
8489 check_spends!(htlc_txn[0], bob_state_y);
8494 fn test_pre_lockin_no_chan_closed_update() {
8495 // Test that if a peer closes a channel in response to a funding_created message we don't
8496 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8499 // Doing so would imply a channel monitor update before the initial channel monitor
8500 // registration, violating our API guarantees.
8502 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8503 // then opening a second channel with the same funding output as the first (which is not
8504 // rejected because the first channel does not exist in the ChannelManager) and closing it
8505 // before receiving funding_signed.
8506 let chanmon_cfgs = create_chanmon_cfgs(2);
8507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8511 // Create an initial channel
8512 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8513 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8514 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8515 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8516 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8518 // Move the first channel through the funding flow...
8519 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8521 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8522 check_added_monitors!(nodes[0], 0);
8524 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8525 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8526 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8527 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8528 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8532 fn test_htlc_no_detection() {
8533 // This test is a mutation to underscore the detection logic bug we had
8534 // before #653. HTLC value routed is above the remaining balance, thus
8535 // inverting HTLC and `to_remote` output. HTLC will come second and
8536 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8537 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8538 // outputs order detection for correct spending children filtring.
8540 let chanmon_cfgs = create_chanmon_cfgs(2);
8541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8543 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8545 // Create some initial channels
8546 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8548 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8549 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8550 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8551 assert_eq!(local_txn[0].input.len(), 1);
8552 assert_eq!(local_txn[0].output.len(), 3);
8553 check_spends!(local_txn[0], chan_1.3);
8555 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8556 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8557 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8558 // We deliberately connect the local tx twice as this should provoke a failure calling
8559 // this test before #653 fix.
8560 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);
8561 check_closed_broadcast!(nodes[0], true);
8562 check_added_monitors!(nodes[0], 1);
8563 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8564 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8566 let htlc_timeout = {
8567 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8568 assert_eq!(node_txn.len(), 1);
8569 assert_eq!(node_txn[0].input.len(), 1);
8570 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8571 check_spends!(node_txn[0], local_txn[0]);
8575 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8576 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8577 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8578 expect_payment_failed!(nodes[0], our_payment_hash, false);
8581 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8582 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8583 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8584 // Carol, Alice would be the upstream node, and Carol the downstream.)
8586 // Steps of the test:
8587 // 1) Alice sends a HTLC to Carol through Bob.
8588 // 2) Carol doesn't settle the HTLC.
8589 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8590 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8591 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8592 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8593 // 5) Carol release the preimage to Bob off-chain.
8594 // 6) Bob claims the offered output on the broadcasted commitment.
8595 let chanmon_cfgs = create_chanmon_cfgs(3);
8596 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8597 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8598 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8600 // Create some initial channels
8601 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8602 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8604 // Steps (1) and (2):
8605 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8606 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8608 // Check that Alice's commitment transaction now contains an output for this HTLC.
8609 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8610 check_spends!(alice_txn[0], chan_ab.3);
8611 assert_eq!(alice_txn[0].output.len(), 2);
8612 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8613 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8614 assert_eq!(alice_txn.len(), 2);
8616 // Steps (3) and (4):
8617 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8618 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8619 let mut force_closing_node = 0; // Alice force-closes
8620 let mut counterparty_node = 1; // Bob if Alice force-closes
8623 if !broadcast_alice {
8624 force_closing_node = 1;
8625 counterparty_node = 0;
8627 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8628 check_closed_broadcast!(nodes[force_closing_node], true);
8629 check_added_monitors!(nodes[force_closing_node], 1);
8630 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8631 if go_onchain_before_fulfill {
8632 let txn_to_broadcast = match broadcast_alice {
8633 true => alice_txn.clone(),
8634 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8636 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8637 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8638 if broadcast_alice {
8639 check_closed_broadcast!(nodes[1], true);
8640 check_added_monitors!(nodes[1], 1);
8641 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8646 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8647 // process of removing the HTLC from their commitment transactions.
8648 nodes[2].node.claim_funds(payment_preimage);
8649 check_added_monitors!(nodes[2], 1);
8650 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8652 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8653 assert!(carol_updates.update_add_htlcs.is_empty());
8654 assert!(carol_updates.update_fail_htlcs.is_empty());
8655 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8656 assert!(carol_updates.update_fee.is_none());
8657 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8659 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8660 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8661 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8662 if !go_onchain_before_fulfill && broadcast_alice {
8663 let events = nodes[1].node.get_and_clear_pending_msg_events();
8664 assert_eq!(events.len(), 1);
8666 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8667 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8669 _ => panic!("Unexpected event"),
8672 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8673 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8674 // Carol<->Bob's updated commitment transaction info.
8675 check_added_monitors!(nodes[1], 2);
8677 let events = nodes[1].node.get_and_clear_pending_msg_events();
8678 assert_eq!(events.len(), 2);
8679 let bob_revocation = match events[0] {
8680 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8681 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8684 _ => panic!("Unexpected event"),
8686 let bob_updates = match events[1] {
8687 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8688 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8691 _ => panic!("Unexpected event"),
8694 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8695 check_added_monitors!(nodes[2], 1);
8696 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8697 check_added_monitors!(nodes[2], 1);
8699 let events = nodes[2].node.get_and_clear_pending_msg_events();
8700 assert_eq!(events.len(), 1);
8701 let carol_revocation = match events[0] {
8702 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8703 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8706 _ => panic!("Unexpected event"),
8708 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8709 check_added_monitors!(nodes[1], 1);
8711 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8712 // here's where we put said channel's commitment tx on-chain.
8713 let mut txn_to_broadcast = alice_txn.clone();
8714 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8715 if !go_onchain_before_fulfill {
8716 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8717 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8718 // If Bob was the one to force-close, he will have already passed these checks earlier.
8719 if broadcast_alice {
8720 check_closed_broadcast!(nodes[1], true);
8721 check_added_monitors!(nodes[1], 1);
8722 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8724 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8725 if broadcast_alice {
8726 assert_eq!(bob_txn.len(), 1);
8727 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8729 assert_eq!(bob_txn.len(), 2);
8730 check_spends!(bob_txn[0], chan_ab.3);
8735 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8736 // broadcasted commitment transaction.
8738 let script_weight = match broadcast_alice {
8739 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8740 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8742 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8743 // Bob force-closed and broadcasts the commitment transaction along with a
8744 // HTLC-output-claiming transaction.
8745 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8746 if broadcast_alice {
8747 assert_eq!(bob_txn.len(), 1);
8748 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8749 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8751 assert_eq!(bob_txn.len(), 2);
8752 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8753 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8759 fn test_onchain_htlc_settlement_after_close() {
8760 do_test_onchain_htlc_settlement_after_close(true, true);
8761 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8762 do_test_onchain_htlc_settlement_after_close(true, false);
8763 do_test_onchain_htlc_settlement_after_close(false, false);
8767 fn test_duplicate_temporary_channel_id_from_different_peers() {
8768 // Tests that we can accept two different `OpenChannel` requests with the same
8769 // `temporary_channel_id`, as long as they are from different peers.
8770 let chanmon_cfgs = create_chanmon_cfgs(3);
8771 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8772 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8773 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8775 // Create an first channel channel
8776 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8777 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8779 // Create an second channel
8780 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8781 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8783 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8784 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8785 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8787 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8788 // `temporary_channel_id` as they are from different peers.
8789 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8791 let events = nodes[0].node.get_and_clear_pending_msg_events();
8792 assert_eq!(events.len(), 1);
8794 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8795 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8796 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8798 _ => panic!("Unexpected event"),
8802 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8804 let events = nodes[0].node.get_and_clear_pending_msg_events();
8805 assert_eq!(events.len(), 1);
8807 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8808 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8809 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8811 _ => panic!("Unexpected event"),
8817 fn test_duplicate_chan_id() {
8818 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8819 // already open we reject it and keep the old channel.
8821 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8822 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8823 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8824 // updating logic for the existing channel.
8825 let chanmon_cfgs = create_chanmon_cfgs(2);
8826 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8827 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8828 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8830 // Create an initial channel
8831 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8832 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8833 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8834 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()));
8836 // Try to create a second channel with the same temporary_channel_id as the first and check
8837 // that it is rejected.
8838 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8840 let events = nodes[1].node.get_and_clear_pending_msg_events();
8841 assert_eq!(events.len(), 1);
8843 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8844 // Technically, at this point, nodes[1] would be justified in thinking both the
8845 // first (valid) and second (invalid) channels are closed, given they both have
8846 // the same non-temporary channel_id. However, currently we do not, so we just
8847 // move forward with it.
8848 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8849 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8851 _ => panic!("Unexpected event"),
8855 // Move the first channel through the funding flow...
8856 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8858 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8859 check_added_monitors!(nodes[0], 0);
8861 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8862 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8864 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8865 assert_eq!(added_monitors.len(), 1);
8866 assert_eq!(added_monitors[0].0, funding_output);
8867 added_monitors.clear();
8869 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8871 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8872 let channel_id = funding_outpoint.to_channel_id();
8874 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8877 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8878 // Technically this is allowed by the spec, but we don't support it and there's little reason
8879 // to. Still, it shouldn't cause any other issues.
8880 open_chan_msg.temporary_channel_id = channel_id;
8881 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8883 let events = nodes[1].node.get_and_clear_pending_msg_events();
8884 assert_eq!(events.len(), 1);
8886 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8887 // Technically, at this point, nodes[1] would be justified in thinking both
8888 // channels are closed, but currently we do not, so we just move forward with it.
8889 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8890 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8892 _ => panic!("Unexpected event"),
8896 // Now try to create a second channel which has a duplicate funding output.
8897 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8898 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8899 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8900 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()));
8901 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8903 let funding_created = {
8904 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8905 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8906 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8907 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8908 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8909 // channelmanager in a possibly nonsense state instead).
8910 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8911 let logger = test_utils::TestLogger::new();
8912 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8914 check_added_monitors!(nodes[0], 0);
8915 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8916 // At this point we'll look up if the channel_id is present and immediately fail the channel
8917 // without trying to persist the `ChannelMonitor`.
8918 check_added_monitors!(nodes[1], 0);
8920 // ...still, nodes[1] will reject the duplicate channel.
8922 let events = nodes[1].node.get_and_clear_pending_msg_events();
8923 assert_eq!(events.len(), 1);
8925 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8926 // Technically, at this point, nodes[1] would be justified in thinking both
8927 // channels are closed, but currently we do not, so we just move forward with it.
8928 assert_eq!(msg.channel_id, channel_id);
8929 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8931 _ => panic!("Unexpected event"),
8935 // finally, finish creating the original channel and send a payment over it to make sure
8936 // everything is functional.
8937 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8939 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8940 assert_eq!(added_monitors.len(), 1);
8941 assert_eq!(added_monitors[0].0, funding_output);
8942 added_monitors.clear();
8945 let events_4 = nodes[0].node.get_and_clear_pending_events();
8946 assert_eq!(events_4.len(), 0);
8947 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8948 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8950 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8951 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8952 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8954 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8958 fn test_error_chans_closed() {
8959 // Test that we properly handle error messages, closing appropriate channels.
8961 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8962 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8963 // we can test various edge cases around it to ensure we don't regress.
8964 let chanmon_cfgs = create_chanmon_cfgs(3);
8965 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8966 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8967 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8969 // Create some initial channels
8970 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8971 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8972 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8974 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8975 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8976 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8978 // Closing a channel from a different peer has no effect
8979 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8980 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8982 // Closing one channel doesn't impact others
8983 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8984 check_added_monitors!(nodes[0], 1);
8985 check_closed_broadcast!(nodes[0], false);
8986 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8987 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8988 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8989 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);
8990 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);
8992 // A null channel ID should close all channels
8993 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8994 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8995 check_added_monitors!(nodes[0], 2);
8996 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8997 let events = nodes[0].node.get_and_clear_pending_msg_events();
8998 assert_eq!(events.len(), 2);
9000 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9001 assert_eq!(msg.contents.flags & 2, 2);
9003 _ => panic!("Unexpected event"),
9006 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9007 assert_eq!(msg.contents.flags & 2, 2);
9009 _ => panic!("Unexpected event"),
9011 // Note that at this point users of a standard PeerHandler will end up calling
9012 // peer_disconnected.
9013 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9014 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9016 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9017 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9018 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9022 fn test_invalid_funding_tx() {
9023 // Test that we properly handle invalid funding transactions sent to us from a peer.
9025 // Previously, all other major lightning implementations had failed to properly sanitize
9026 // funding transactions from their counterparties, leading to a multi-implementation critical
9027 // security vulnerability (though we always sanitized properly, we've previously had
9028 // un-released crashes in the sanitization process).
9030 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9031 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9032 // gave up on it. We test this here by generating such a transaction.
9033 let chanmon_cfgs = create_chanmon_cfgs(2);
9034 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9035 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9036 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9038 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9039 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()));
9040 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()));
9042 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9044 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9045 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9046 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9048 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9049 let wit_program_script: Script = wit_program.into();
9050 for output in tx.output.iter_mut() {
9051 // Make the confirmed funding transaction have a bogus script_pubkey
9052 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9055 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9056 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()));
9057 check_added_monitors!(nodes[1], 1);
9059 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()));
9060 check_added_monitors!(nodes[0], 1);
9062 let events_1 = nodes[0].node.get_and_clear_pending_events();
9063 assert_eq!(events_1.len(), 0);
9065 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9066 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9067 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9069 let expected_err = "funding tx had wrong script/value or output index";
9070 confirm_transaction_at(&nodes[1], &tx, 1);
9071 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9072 check_added_monitors!(nodes[1], 1);
9073 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9074 assert_eq!(events_2.len(), 1);
9075 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9076 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9077 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9078 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9079 } else { panic!(); }
9080 } else { panic!(); }
9081 assert_eq!(nodes[1].node.list_channels().len(), 0);
9083 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9084 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9085 // as its not 32 bytes long.
9086 let mut spend_tx = Transaction {
9087 version: 2i32, lock_time: PackedLockTime::ZERO,
9088 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9089 previous_output: BitcoinOutPoint {
9093 script_sig: Script::new(),
9094 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9095 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9097 output: vec![TxOut {
9099 script_pubkey: Script::new(),
9102 check_spends!(spend_tx, tx);
9103 mine_transaction(&nodes[1], &spend_tx);
9106 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9107 // In the first version of the chain::Confirm interface, after a refactor was made to not
9108 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9109 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9110 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9111 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9112 // spending transaction until height N+1 (or greater). This was due to the way
9113 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9114 // spending transaction at the height the input transaction was confirmed at, not whether we
9115 // should broadcast a spending transaction at the current height.
9116 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9117 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9118 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9119 // until we learned about an additional block.
9121 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9122 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9123 let chanmon_cfgs = create_chanmon_cfgs(3);
9124 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9125 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9126 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9127 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9129 create_announced_chan_between_nodes(&nodes, 0, 1);
9130 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9131 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9132 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9133 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9135 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9136 check_closed_broadcast!(nodes[1], true);
9137 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9138 check_added_monitors!(nodes[1], 1);
9139 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9140 assert_eq!(node_txn.len(), 1);
9142 let conf_height = nodes[1].best_block_info().1;
9143 if !test_height_before_timelock {
9144 connect_blocks(&nodes[1], 24 * 6);
9146 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9147 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9148 if test_height_before_timelock {
9149 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9150 // generate any events or broadcast any transactions
9151 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9152 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9154 // We should broadcast an HTLC transaction spending our funding transaction first
9155 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9156 assert_eq!(spending_txn.len(), 2);
9157 assert_eq!(spending_txn[0], node_txn[0]);
9158 check_spends!(spending_txn[1], node_txn[0]);
9159 // We should also generate a SpendableOutputs event with the to_self output (as its
9161 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9162 assert_eq!(descriptor_spend_txn.len(), 1);
9164 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9165 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9166 // additional block built on top of the current chain.
9167 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9168 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9169 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 }]);
9170 check_added_monitors!(nodes[1], 1);
9172 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9173 assert!(updates.update_add_htlcs.is_empty());
9174 assert!(updates.update_fulfill_htlcs.is_empty());
9175 assert_eq!(updates.update_fail_htlcs.len(), 1);
9176 assert!(updates.update_fail_malformed_htlcs.is_empty());
9177 assert!(updates.update_fee.is_none());
9178 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9179 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9180 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9185 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9186 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9187 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9190 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9191 let chanmon_cfgs = create_chanmon_cfgs(2);
9192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9194 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9196 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9198 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9199 .with_features(nodes[1].node.invoice_features());
9200 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9202 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9205 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9206 check_added_monitors!(nodes[0], 1);
9207 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9208 assert_eq!(events.len(), 1);
9209 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9210 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9211 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9213 expect_pending_htlcs_forwardable!(nodes[1]);
9214 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9217 // Note that we use a different PaymentId here to allow us to duplicativly pay
9218 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9219 check_added_monitors!(nodes[0], 1);
9220 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9221 assert_eq!(events.len(), 1);
9222 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9223 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9224 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9225 // At this point, nodes[1] would notice it has too much value for the payment. It will
9226 // assume the second is a privacy attack (no longer particularly relevant
9227 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9228 // the first HTLC delivered above.
9231 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9232 nodes[1].node.process_pending_htlc_forwards();
9234 if test_for_second_fail_panic {
9235 // Now we go fail back the first HTLC from the user end.
9236 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9238 let expected_destinations = vec![
9239 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9240 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9242 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9243 nodes[1].node.process_pending_htlc_forwards();
9245 check_added_monitors!(nodes[1], 1);
9246 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9247 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9249 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9250 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9251 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9253 let failure_events = nodes[0].node.get_and_clear_pending_events();
9254 assert_eq!(failure_events.len(), 4);
9255 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9256 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9257 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9258 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9260 // Let the second HTLC fail and claim the first
9261 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9262 nodes[1].node.process_pending_htlc_forwards();
9264 check_added_monitors!(nodes[1], 1);
9265 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9266 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9267 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9269 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9271 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9276 fn test_dup_htlc_second_fail_panic() {
9277 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9278 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9279 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9280 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9281 do_test_dup_htlc_second_rejected(true);
9285 fn test_dup_htlc_second_rejected() {
9286 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9287 // simply reject the second HTLC but are still able to claim the first HTLC.
9288 do_test_dup_htlc_second_rejected(false);
9292 fn test_inconsistent_mpp_params() {
9293 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9294 // such HTLC and allow the second to stay.
9295 let chanmon_cfgs = create_chanmon_cfgs(4);
9296 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9297 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9298 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9300 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9301 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9302 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9303 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9305 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9306 .with_features(nodes[3].node.invoice_features());
9307 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9308 assert_eq!(route.paths.len(), 2);
9309 route.paths.sort_by(|path_a, _| {
9310 // Sort the path so that the path through nodes[1] comes first
9311 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9312 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9315 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9317 let cur_height = nodes[0].best_block_info().1;
9318 let payment_id = PaymentId([42; 32]);
9320 let session_privs = {
9321 // We create a fake route here so that we start with three pending HTLCs, which we'll
9322 // ultimately have, just not right away.
9323 let mut dup_route = route.clone();
9324 dup_route.paths.push(route.paths[1].clone());
9325 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9327 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();
9328 check_added_monitors!(nodes[0], 1);
9331 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9332 assert_eq!(events.len(), 1);
9333 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9335 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9337 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();
9338 check_added_monitors!(nodes[0], 1);
9341 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9342 assert_eq!(events.len(), 1);
9343 let payment_event = SendEvent::from_event(events.pop().unwrap());
9345 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9346 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9348 expect_pending_htlcs_forwardable!(nodes[2]);
9349 check_added_monitors!(nodes[2], 1);
9351 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9352 assert_eq!(events.len(), 1);
9353 let payment_event = SendEvent::from_event(events.pop().unwrap());
9355 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9356 check_added_monitors!(nodes[3], 0);
9357 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9359 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9360 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9361 // post-payment_secrets) and fail back the new HTLC.
9363 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9364 nodes[3].node.process_pending_htlc_forwards();
9365 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9366 nodes[3].node.process_pending_htlc_forwards();
9368 check_added_monitors!(nodes[3], 1);
9370 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9371 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9372 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9374 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 }]);
9375 check_added_monitors!(nodes[2], 1);
9377 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9378 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9379 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9381 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9383 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();
9384 check_added_monitors!(nodes[0], 1);
9386 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9387 assert_eq!(events.len(), 1);
9388 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9390 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9391 let events = nodes[0].node.get_and_clear_pending_events();
9392 assert_eq!(events.len(), 3);
9394 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9395 assert_eq!(payment_hash, our_payment_hash);
9397 _ => panic!("Unexpected event")
9400 Event::PaymentPathSuccessful { payment_hash, .. } => {
9401 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9403 _ => panic!("Unexpected event")
9406 Event::PaymentPathSuccessful { payment_hash, .. } => {
9407 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9409 _ => panic!("Unexpected event")
9414 fn test_keysend_payments_to_public_node() {
9415 let chanmon_cfgs = create_chanmon_cfgs(2);
9416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9420 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9421 let network_graph = nodes[0].network_graph.clone();
9422 let payer_pubkey = nodes[0].node.get_our_node_id();
9423 let payee_pubkey = nodes[1].node.get_our_node_id();
9424 let route_params = RouteParameters {
9425 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9426 final_value_msat: 10000,
9428 let scorer = test_utils::TestScorer::new();
9429 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9430 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9432 let test_preimage = PaymentPreimage([42; 32]);
9433 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9434 check_added_monitors!(nodes[0], 1);
9435 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9436 assert_eq!(events.len(), 1);
9437 let event = events.pop().unwrap();
9438 let path = vec![&nodes[1]];
9439 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9440 claim_payment(&nodes[0], &path, test_preimage);
9444 fn test_keysend_payments_to_private_node() {
9445 let chanmon_cfgs = create_chanmon_cfgs(2);
9446 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9447 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9448 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9450 let payer_pubkey = nodes[0].node.get_our_node_id();
9451 let payee_pubkey = nodes[1].node.get_our_node_id();
9453 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9454 let route_params = RouteParameters {
9455 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9456 final_value_msat: 10000,
9458 let network_graph = nodes[0].network_graph.clone();
9459 let first_hops = nodes[0].node.list_usable_channels();
9460 let scorer = test_utils::TestScorer::new();
9461 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9462 let route = find_route(
9463 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9464 nodes[0].logger, &scorer, &random_seed_bytes
9467 let test_preimage = PaymentPreimage([42; 32]);
9468 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9469 check_added_monitors!(nodes[0], 1);
9470 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9471 assert_eq!(events.len(), 1);
9472 let event = events.pop().unwrap();
9473 let path = vec![&nodes[1]];
9474 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9475 claim_payment(&nodes[0], &path, test_preimage);
9479 fn test_double_partial_claim() {
9480 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9481 // time out, the sender resends only some of the MPP parts, then the user processes the
9482 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9484 let chanmon_cfgs = create_chanmon_cfgs(4);
9485 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9486 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9487 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9489 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9490 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9491 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9492 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9494 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9495 assert_eq!(route.paths.len(), 2);
9496 route.paths.sort_by(|path_a, _| {
9497 // Sort the path so that the path through nodes[1] comes first
9498 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9499 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9502 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9503 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9504 // amount of time to respond to.
9506 // Connect some blocks to time out the payment
9507 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9508 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9510 let failed_destinations = vec![
9511 HTLCDestination::FailedPayment { payment_hash },
9512 HTLCDestination::FailedPayment { payment_hash },
9514 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9516 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9518 // nodes[1] now retries one of the two paths...
9519 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9520 check_added_monitors!(nodes[0], 2);
9522 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9523 assert_eq!(events.len(), 2);
9524 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9525 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9527 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9528 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9529 nodes[3].node.claim_funds(payment_preimage);
9530 check_added_monitors!(nodes[3], 0);
9531 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9534 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9535 #[derive(Clone, Copy, PartialEq)]
9536 enum ExposureEvent {
9537 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9539 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9541 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9542 AtUpdateFeeOutbound,
9545 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9546 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9549 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9550 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9551 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9552 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9553 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9554 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9555 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9556 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9558 let chanmon_cfgs = create_chanmon_cfgs(2);
9559 let mut config = test_default_channel_config();
9560 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9563 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9565 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9566 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9567 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9568 open_channel.max_accepted_htlcs = 60;
9570 open_channel.dust_limit_satoshis = 546;
9572 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9573 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9574 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9576 let opt_anchors = false;
9578 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9581 let mut node_0_per_peer_lock;
9582 let mut node_0_peer_state_lock;
9583 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9584 chan.holder_dust_limit_satoshis = 546;
9587 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9588 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()));
9589 check_added_monitors!(nodes[1], 1);
9591 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()));
9592 check_added_monitors!(nodes[0], 1);
9594 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9595 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9596 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9598 let dust_buffer_feerate = {
9599 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9600 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9601 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9602 chan.get_dust_buffer_feerate(None) as u64
9604 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;
9605 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9607 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;
9608 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9610 let dust_htlc_on_counterparty_tx: u64 = 25;
9611 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9614 if dust_outbound_balance {
9615 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9616 // Outbound dust balance: 4372 sats
9617 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9618 for i in 0..dust_outbound_htlc_on_holder_tx {
9619 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9620 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); }
9623 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9624 // Inbound dust balance: 4372 sats
9625 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9626 for _ in 0..dust_inbound_htlc_on_holder_tx {
9627 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9631 if dust_outbound_balance {
9632 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9633 // Outbound dust balance: 5000 sats
9634 for i in 0..dust_htlc_on_counterparty_tx {
9635 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9636 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); }
9639 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9640 // Inbound dust balance: 5000 sats
9641 for _ in 0..dust_htlc_on_counterparty_tx {
9642 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9647 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9648 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9649 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 });
9650 let mut config = UserConfig::default();
9651 // With default dust exposure: 5000 sats
9653 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9654 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_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 holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9657 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)));
9659 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9660 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 });
9661 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9662 check_added_monitors!(nodes[1], 1);
9663 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9664 assert_eq!(events.len(), 1);
9665 let payment_event = SendEvent::from_event(events.remove(0));
9666 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9667 // With default dust exposure: 5000 sats
9669 // Outbound dust balance: 6399 sats
9670 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9671 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9672 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);
9674 // Outbound dust balance: 5200 sats
9675 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);
9677 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9678 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9679 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", ); }
9681 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9682 *feerate_lock = *feerate_lock * 10;
9684 nodes[0].node.timer_tick_occurred();
9685 check_added_monitors!(nodes[0], 1);
9686 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9689 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9690 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9691 added_monitors.clear();
9695 fn test_max_dust_htlc_exposure() {
9696 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9697 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9698 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9699 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9700 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9701 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9702 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9703 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9704 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9705 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9706 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9707 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9711 fn test_non_final_funding_tx() {
9712 let chanmon_cfgs = create_chanmon_cfgs(2);
9713 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9714 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9715 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9717 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9718 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9719 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9720 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9721 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9723 let best_height = nodes[0].node.best_block.read().unwrap().height();
9725 let chan_id = *nodes[0].network_chan_count.borrow();
9726 let events = nodes[0].node.get_and_clear_pending_events();
9727 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9728 assert_eq!(events.len(), 1);
9729 let mut tx = match events[0] {
9730 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9731 // Timelock the transaction _beyond_ the best client height + 2.
9732 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9733 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9736 _ => panic!("Unexpected event"),
9738 // Transaction should fail as it's evaluated as non-final for propagation.
9739 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9740 Err(APIError::APIMisuseError { err }) => {
9741 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9746 // However, transaction should be accepted if it's in a +2 headroom from best block.
9747 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9748 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9749 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9753 fn accept_busted_but_better_fee() {
9754 // If a peer sends us a fee update that is too low, but higher than our previous channel
9755 // feerate, we should accept it. In the future we may want to consider closing the channel
9756 // later, but for now we only accept the update.
9757 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9760 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9762 create_chan_between_nodes(&nodes[0], &nodes[1]);
9764 // Set nodes[1] to expect 5,000 sat/kW.
9766 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9767 *feerate_lock = 5000;
9770 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9772 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9773 *feerate_lock = 1000;
9775 nodes[0].node.timer_tick_occurred();
9776 check_added_monitors!(nodes[0], 1);
9778 let events = nodes[0].node.get_and_clear_pending_msg_events();
9779 assert_eq!(events.len(), 1);
9781 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9782 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9783 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9785 _ => panic!("Unexpected event"),
9788 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9791 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9792 *feerate_lock = 2000;
9794 nodes[0].node.timer_tick_occurred();
9795 check_added_monitors!(nodes[0], 1);
9797 let events = nodes[0].node.get_and_clear_pending_msg_events();
9798 assert_eq!(events.len(), 1);
9800 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9801 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9802 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9804 _ => panic!("Unexpected event"),
9807 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9810 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9811 *feerate_lock = 1000;
9813 nodes[0].node.timer_tick_occurred();
9814 check_added_monitors!(nodes[0], 1);
9816 let events = nodes[0].node.get_and_clear_pending_msg_events();
9817 assert_eq!(events.len(), 1);
9819 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9820 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9821 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9822 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9823 check_closed_broadcast!(nodes[1], true);
9824 check_added_monitors!(nodes[1], 1);
9826 _ => panic!("Unexpected event"),
9830 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9831 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9834 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9835 let min_final_cltv_expiry_delta = 120;
9836 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9837 min_final_cltv_expiry_delta - 2 };
9838 let recv_value = 100_000;
9840 create_chan_between_nodes(&nodes[0], &nodes[1]);
9842 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9843 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9844 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9845 Some(recv_value), Some(min_final_cltv_expiry_delta));
9846 (payment_hash, payment_preimage, payment_secret)
9848 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9849 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9851 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9852 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9853 check_added_monitors!(nodes[0], 1);
9854 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9855 assert_eq!(events.len(), 1);
9856 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9857 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9858 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9859 expect_pending_htlcs_forwardable!(nodes[1]);
9862 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9863 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9865 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9867 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9869 check_added_monitors!(nodes[1], 1);
9871 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9872 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9873 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9875 expect_payment_failed!(nodes[0], payment_hash, true);
9880 fn test_payment_with_custom_min_cltv_expiry_delta() {
9881 do_payment_with_custom_min_final_cltv_expiry(false, false);
9882 do_payment_with_custom_min_final_cltv_expiry(false, true);
9883 do_payment_with_custom_min_final_cltv_expiry(true, false);
9884 do_payment_with_custom_min_final_cltv_expiry(true, true);