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
741 let update_fee = msgs::UpdateFee {
743 feerate_per_kw: non_buffer_feerate + 4,
746 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
748 //While producing the commitment_signed response after handling a received update_fee request the
749 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
750 //Should produce and error.
751 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
752 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
753 check_added_monitors!(nodes[1], 1);
754 check_closed_broadcast!(nodes[1], true);
755 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
759 fn test_update_fee_with_fundee_update_add_htlc() {
760 let chanmon_cfgs = create_chanmon_cfgs(2);
761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
763 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
764 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
767 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
770 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
773 nodes[0].node.timer_tick_occurred();
774 check_added_monitors!(nodes[0], 1);
776 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
777 assert_eq!(events_0.len(), 1);
778 let (update_msg, commitment_signed) = match events_0[0] {
779 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 } } => {
780 (update_fee.as_ref(), commitment_signed)
782 _ => panic!("Unexpected event"),
784 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
785 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
786 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
787 check_added_monitors!(nodes[1], 1);
789 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
791 // nothing happens since node[1] is in AwaitingRemoteRevoke
792 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
794 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
795 assert_eq!(added_monitors.len(), 0);
796 added_monitors.clear();
798 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
799 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
800 // node[1] has nothing to do
802 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 check_added_monitors!(nodes[0], 1);
806 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
807 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
808 // No commitment_signed so get_event_msg's assert(len == 1) passes
809 check_added_monitors!(nodes[0], 1);
810 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
811 check_added_monitors!(nodes[1], 1);
812 // AwaitingRemoteRevoke ends here
814 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
815 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
816 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
817 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
818 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
819 assert_eq!(commitment_update.update_fee.is_none(), true);
821 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
822 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
823 check_added_monitors!(nodes[0], 1);
824 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
826 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
827 check_added_monitors!(nodes[1], 1);
828 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
830 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
831 check_added_monitors!(nodes[1], 1);
832 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
833 // No commitment_signed so get_event_msg's assert(len == 1) passes
835 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
836 check_added_monitors!(nodes[0], 1);
837 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
839 expect_pending_htlcs_forwardable!(nodes[0]);
841 let events = nodes[0].node.get_and_clear_pending_events();
842 assert_eq!(events.len(), 1);
844 Event::PaymentClaimable { .. } => { },
845 _ => panic!("Unexpected event"),
848 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
850 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
851 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
852 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
853 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
854 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
858 fn test_update_fee() {
859 let chanmon_cfgs = create_chanmon_cfgs(2);
860 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
861 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
862 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
863 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
864 let channel_id = chan.2;
867 // (1) update_fee/commitment_signed ->
868 // <- (2) revoke_and_ack
869 // .- send (3) commitment_signed
870 // (4) update_fee/commitment_signed ->
871 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
872 // <- (3) commitment_signed delivered
873 // send (6) revoke_and_ack -.
874 // <- (5) deliver revoke_and_ack
875 // (6) deliver revoke_and_ack ->
876 // .- send (7) commitment_signed in response to (4)
877 // <- (7) deliver commitment_signed
880 // Create and deliver (1)...
883 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
884 feerate = *feerate_lock;
885 *feerate_lock = feerate + 20;
887 nodes[0].node.timer_tick_occurred();
888 check_added_monitors!(nodes[0], 1);
890 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
891 assert_eq!(events_0.len(), 1);
892 let (update_msg, commitment_signed) = match events_0[0] {
893 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 } } => {
894 (update_fee.as_ref(), commitment_signed)
896 _ => panic!("Unexpected event"),
898 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
900 // Generate (2) and (3):
901 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
902 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
903 check_added_monitors!(nodes[1], 1);
906 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
907 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
908 check_added_monitors!(nodes[0], 1);
910 // Create and deliver (4)...
912 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
913 *feerate_lock = feerate + 30;
915 nodes[0].node.timer_tick_occurred();
916 check_added_monitors!(nodes[0], 1);
917 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
918 assert_eq!(events_0.len(), 1);
919 let (update_msg, commitment_signed) = match events_0[0] {
920 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 } } => {
921 (update_fee.as_ref(), commitment_signed)
923 _ => panic!("Unexpected event"),
926 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
927 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
928 check_added_monitors!(nodes[1], 1);
930 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
931 // No commitment_signed so get_event_msg's assert(len == 1) passes
933 // Handle (3), creating (6):
934 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
935 check_added_monitors!(nodes[0], 1);
936 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
937 // No commitment_signed so get_event_msg's assert(len == 1) passes
940 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
941 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
942 check_added_monitors!(nodes[0], 1);
944 // Deliver (6), creating (7):
945 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
946 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
947 assert!(commitment_update.update_add_htlcs.is_empty());
948 assert!(commitment_update.update_fulfill_htlcs.is_empty());
949 assert!(commitment_update.update_fail_htlcs.is_empty());
950 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
951 assert!(commitment_update.update_fee.is_none());
952 check_added_monitors!(nodes[1], 1);
955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
956 check_added_monitors!(nodes[0], 1);
957 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958 // No commitment_signed so get_event_msg's assert(len == 1) passes
960 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
961 check_added_monitors!(nodes[1], 1);
962 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
964 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
965 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
966 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
967 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
968 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
972 fn fake_network_test() {
973 // Simple test which builds a network of ChannelManagers, connects them to each other, and
974 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
975 let chanmon_cfgs = create_chanmon_cfgs(4);
976 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
977 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
978 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
980 // Create some initial channels
981 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
982 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
983 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
985 // Rebalance the network a bit by relaying one payment through all the channels...
986 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
987 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
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);
991 // Send some more payments
992 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
993 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
994 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
996 // Test failure packets
997 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
998 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1000 // Add a new channel that skips 3
1001 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1003 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1004 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1005 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1006 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
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);
1011 // Do some rebalance loop payments, simultaneously
1012 let mut hops = Vec::with_capacity(3);
1013 hops.push(RouteHop {
1014 pubkey: nodes[2].node.get_our_node_id(),
1015 node_features: NodeFeatures::empty(),
1016 short_channel_id: chan_2.0.contents.short_channel_id,
1017 channel_features: ChannelFeatures::empty(),
1019 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1021 hops.push(RouteHop {
1022 pubkey: nodes[3].node.get_our_node_id(),
1023 node_features: NodeFeatures::empty(),
1024 short_channel_id: chan_3.0.contents.short_channel_id,
1025 channel_features: ChannelFeatures::empty(),
1027 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1029 hops.push(RouteHop {
1030 pubkey: nodes[1].node.get_our_node_id(),
1031 node_features: nodes[1].node.node_features(),
1032 short_channel_id: chan_4.0.contents.short_channel_id,
1033 channel_features: nodes[1].node.channel_features(),
1035 cltv_expiry_delta: TEST_FINAL_CLTV,
1037 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;
1038 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;
1039 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;
1041 let mut hops = Vec::with_capacity(3);
1042 hops.push(RouteHop {
1043 pubkey: nodes[3].node.get_our_node_id(),
1044 node_features: NodeFeatures::empty(),
1045 short_channel_id: chan_4.0.contents.short_channel_id,
1046 channel_features: ChannelFeatures::empty(),
1048 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1050 hops.push(RouteHop {
1051 pubkey: nodes[2].node.get_our_node_id(),
1052 node_features: NodeFeatures::empty(),
1053 short_channel_id: chan_3.0.contents.short_channel_id,
1054 channel_features: ChannelFeatures::empty(),
1056 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1058 hops.push(RouteHop {
1059 pubkey: nodes[1].node.get_our_node_id(),
1060 node_features: nodes[1].node.node_features(),
1061 short_channel_id: chan_2.0.contents.short_channel_id,
1062 channel_features: nodes[1].node.channel_features(),
1064 cltv_expiry_delta: TEST_FINAL_CLTV,
1066 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;
1067 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;
1068 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;
1070 // Claim the rebalances...
1071 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1072 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1074 // Close down the channels...
1075 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1076 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1077 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1078 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1079 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1080 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1081 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1082 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1083 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1084 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1085 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1090 fn holding_cell_htlc_counting() {
1091 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1092 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1093 // commitment dance rounds.
1094 let chanmon_cfgs = create_chanmon_cfgs(3);
1095 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1096 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1097 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1098 create_announced_chan_between_nodes(&nodes, 0, 1);
1099 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1101 let mut payments = Vec::new();
1102 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1103 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1104 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
1105 payments.push((payment_preimage, payment_hash));
1107 check_added_monitors!(nodes[1], 1);
1109 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1110 assert_eq!(events.len(), 1);
1111 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1112 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1114 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1115 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1117 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1119 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 },
1120 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1121 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1122 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1125 // This should also be true if we try to forward a payment.
1126 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1128 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1129 check_added_monitors!(nodes[0], 1);
1132 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1133 assert_eq!(events.len(), 1);
1134 let payment_event = SendEvent::from_event(events.pop().unwrap());
1135 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1137 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1138 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1139 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1140 // fails), the second will process the resulting failure and fail the HTLC backward.
1141 expect_pending_htlcs_forwardable!(nodes[1]);
1142 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 }]);
1143 check_added_monitors!(nodes[1], 1);
1145 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1146 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1147 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1149 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1151 // Now forward all the pending HTLCs and claim them back
1152 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1153 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1154 check_added_monitors!(nodes[2], 1);
1156 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1157 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1158 check_added_monitors!(nodes[1], 1);
1159 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1161 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1162 check_added_monitors!(nodes[1], 1);
1163 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1165 for ref update in as_updates.update_add_htlcs.iter() {
1166 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1168 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1169 check_added_monitors!(nodes[2], 1);
1170 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1171 check_added_monitors!(nodes[2], 1);
1172 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1174 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1175 check_added_monitors!(nodes[1], 1);
1176 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1177 check_added_monitors!(nodes[1], 1);
1178 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1181 check_added_monitors!(nodes[2], 1);
1183 expect_pending_htlcs_forwardable!(nodes[2]);
1185 let events = nodes[2].node.get_and_clear_pending_events();
1186 assert_eq!(events.len(), payments.len());
1187 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1189 &Event::PaymentClaimable { ref payment_hash, .. } => {
1190 assert_eq!(*payment_hash, *hash);
1192 _ => panic!("Unexpected event"),
1196 for (preimage, _) in payments.drain(..) {
1197 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1200 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1204 fn duplicate_htlc_test() {
1205 // Test that we accept duplicate payment_hash HTLCs across the network and that
1206 // claiming/failing them are all separate and don't affect each other
1207 let chanmon_cfgs = create_chanmon_cfgs(6);
1208 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1209 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1210 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1212 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1213 create_announced_chan_between_nodes(&nodes, 0, 3);
1214 create_announced_chan_between_nodes(&nodes, 1, 3);
1215 create_announced_chan_between_nodes(&nodes, 2, 3);
1216 create_announced_chan_between_nodes(&nodes, 3, 4);
1217 create_announced_chan_between_nodes(&nodes, 3, 5);
1219 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1221 *nodes[0].network_payment_count.borrow_mut() -= 1;
1222 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1224 *nodes[0].network_payment_count.borrow_mut() -= 1;
1225 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1227 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1228 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1229 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1233 fn test_duplicate_htlc_different_direction_onchain() {
1234 // Test that ChannelMonitor doesn't generate 2 preimage txn
1235 // when we have 2 HTLCs with same preimage that go across a node
1236 // in opposite directions, even with the same payment secret.
1237 let chanmon_cfgs = create_chanmon_cfgs(2);
1238 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1239 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1240 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1242 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1245 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1247 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1249 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1250 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1251 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1253 // Provide preimage to node 0 by claiming payment
1254 nodes[0].node.claim_funds(payment_preimage);
1255 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1256 check_added_monitors!(nodes[0], 1);
1258 // Broadcast node 1 commitment txn
1259 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1261 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1262 let mut has_both_htlcs = 0; // check htlcs match ones committed
1263 for outp in remote_txn[0].output.iter() {
1264 if outp.value == 800_000 / 1000 {
1265 has_both_htlcs += 1;
1266 } else if outp.value == 900_000 / 1000 {
1267 has_both_htlcs += 1;
1270 assert_eq!(has_both_htlcs, 2);
1272 mine_transaction(&nodes[0], &remote_txn[0]);
1273 check_added_monitors!(nodes[0], 1);
1274 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1275 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1277 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1278 assert_eq!(claim_txn.len(), 3);
1280 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1281 check_spends!(claim_txn[1], remote_txn[0]);
1282 check_spends!(claim_txn[2], remote_txn[0]);
1283 let preimage_tx = &claim_txn[0];
1284 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1285 (&claim_txn[1], &claim_txn[2])
1287 (&claim_txn[2], &claim_txn[1])
1290 assert_eq!(preimage_tx.input.len(), 1);
1291 assert_eq!(preimage_bump_tx.input.len(), 1);
1293 assert_eq!(preimage_tx.input.len(), 1);
1294 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1295 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1297 assert_eq!(timeout_tx.input.len(), 1);
1298 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1299 check_spends!(timeout_tx, remote_txn[0]);
1300 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1302 let events = nodes[0].node.get_and_clear_pending_msg_events();
1303 assert_eq!(events.len(), 3);
1306 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1307 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1308 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1309 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1311 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, .. } } => {
1312 assert!(update_add_htlcs.is_empty());
1313 assert!(update_fail_htlcs.is_empty());
1314 assert_eq!(update_fulfill_htlcs.len(), 1);
1315 assert!(update_fail_malformed_htlcs.is_empty());
1316 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1318 _ => panic!("Unexpected event"),
1324 fn test_basic_channel_reserve() {
1325 let chanmon_cfgs = create_chanmon_cfgs(2);
1326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1329 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1331 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1332 let channel_reserve = chan_stat.channel_reserve_msat;
1334 // The 2* and +1 are for the fee spike reserve.
1335 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));
1336 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1337 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1338 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1340 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1342 &APIError::ChannelUnavailable{ref err} =>
1343 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1344 _ => panic!("Unexpected error variant"),
1347 _ => panic!("Unexpected error variant"),
1349 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1350 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1352 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1356 fn test_fee_spike_violation_fails_htlc() {
1357 let chanmon_cfgs = create_chanmon_cfgs(2);
1358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1360 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1361 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1363 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1364 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1365 let secp_ctx = Secp256k1::new();
1366 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1368 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1370 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1371 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1372 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1373 let msg = msgs::UpdateAddHTLC {
1376 amount_msat: htlc_msat,
1377 payment_hash: payment_hash,
1378 cltv_expiry: htlc_cltv,
1379 onion_routing_packet: onion_packet,
1382 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1384 // Now manually create the commitment_signed message corresponding to the update_add
1385 // nodes[0] just sent. In the code for construction of this message, "local" refers
1386 // to the sender of the message, and "remote" refers to the receiver.
1388 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1390 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1392 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1393 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1394 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1395 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1396 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1397 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1398 let chan_signer = local_chan.get_signer();
1399 // Make the signer believe we validated another commitment, so we can release the secret
1400 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1402 let pubkeys = chan_signer.pubkeys();
1403 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1404 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1405 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1406 chan_signer.pubkeys().funding_pubkey)
1408 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1409 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1410 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1411 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412 let chan_signer = remote_chan.get_signer();
1413 let pubkeys = chan_signer.pubkeys();
1414 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1415 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1416 chan_signer.pubkeys().funding_pubkey)
1419 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1420 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1421 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1423 // Build the remote commitment transaction so we can sign it, and then later use the
1424 // signature for the commitment_signed message.
1425 let local_chan_balance = 1313;
1427 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1429 amount_msat: 3460001,
1430 cltv_expiry: htlc_cltv,
1432 transaction_output_index: Some(1),
1435 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1438 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1439 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1440 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1441 let local_chan_signer = local_chan.get_signer();
1442 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1446 local_chan.opt_anchors(), local_funding, remote_funding,
1447 commit_tx_keys.clone(),
1449 &mut vec![(accepted_htlc_info, ())],
1450 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1452 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1455 let commit_signed_msg = msgs::CommitmentSigned {
1458 htlc_signatures: res.1
1461 // Send the commitment_signed message to the nodes[1].
1462 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1463 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1465 // Send the RAA to nodes[1].
1466 let raa_msg = msgs::RevokeAndACK {
1468 per_commitment_secret: local_secret,
1469 next_per_commitment_point: next_local_point
1471 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1473 let events = nodes[1].node.get_and_clear_pending_msg_events();
1474 assert_eq!(events.len(), 1);
1475 // Make sure the HTLC failed in the way we expect.
1477 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1478 assert_eq!(update_fail_htlcs.len(), 1);
1479 update_fail_htlcs[0].clone()
1481 _ => panic!("Unexpected event"),
1483 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1484 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1486 check_added_monitors!(nodes[1], 2);
1490 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1491 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1492 // Set the fee rate for the channel very high, to the point where the fundee
1493 // sending any above-dust amount would result in a channel reserve violation.
1494 // In this test we check that we would be prevented from sending an HTLC in
1496 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1499 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1500 let default_config = UserConfig::default();
1501 let opt_anchors = false;
1503 let mut push_amt = 100_000_000;
1504 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1506 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1508 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1510 // Sending exactly enough to hit the reserve amount should be accepted
1511 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1512 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1515 // However one more HTLC should be significantly over the reserve amount and fail.
1516 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1517 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 },
1518 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1519 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1520 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);
1524 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1525 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1526 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1529 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1530 let default_config = UserConfig::default();
1531 let opt_anchors = false;
1533 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1534 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1535 // transaction fee with 0 HTLCs (183 sats)).
1536 let mut push_amt = 100_000_000;
1537 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1538 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1539 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1541 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1542 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1543 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1546 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1547 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1548 let secp_ctx = Secp256k1::new();
1549 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1550 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1551 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1552 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1553 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1554 let msg = msgs::UpdateAddHTLC {
1556 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1557 amount_msat: htlc_msat,
1558 payment_hash: payment_hash,
1559 cltv_expiry: htlc_cltv,
1560 onion_routing_packet: onion_packet,
1563 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1564 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1565 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);
1566 assert_eq!(nodes[0].node.list_channels().len(), 0);
1567 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1568 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1569 check_added_monitors!(nodes[0], 1);
1570 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() });
1574 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1575 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1576 // calculating our commitment transaction fee (this was previously broken).
1577 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1578 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1582 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1583 let default_config = UserConfig::default();
1584 let opt_anchors = false;
1586 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1587 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1588 // transaction fee with 0 HTLCs (183 sats)).
1589 let mut push_amt = 100_000_000;
1590 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1591 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1592 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1594 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1595 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1596 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1597 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1598 // commitment transaction fee.
1599 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1601 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1602 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1603 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1606 // One more than the dust amt should fail, however.
1607 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1608 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 },
1609 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1613 fn test_chan_init_feerate_unaffordability() {
1614 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1615 // channel reserve and feerate requirements.
1616 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1617 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1620 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1621 let default_config = UserConfig::default();
1622 let opt_anchors = false;
1624 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1626 let mut push_amt = 100_000_000;
1627 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1628 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1629 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1631 // During open, we don't have a "counterparty channel reserve" to check against, so that
1632 // requirement only comes into play on the open_channel handling side.
1633 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1634 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1635 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1636 open_channel_msg.push_msat += 1;
1637 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1639 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1640 assert_eq!(msg_events.len(), 1);
1641 match msg_events[0] {
1642 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1643 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1645 _ => panic!("Unexpected event"),
1650 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1651 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1652 // calculating our counterparty's commitment transaction fee (this was previously broken).
1653 let chanmon_cfgs = create_chanmon_cfgs(2);
1654 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1655 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1656 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1657 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1659 let payment_amt = 46000; // Dust amount
1660 // In the previous code, these first four payments would succeed.
1661 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1662 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1663 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1664 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1666 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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);
1671 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1673 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1674 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1675 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1676 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1681 let chanmon_cfgs = create_chanmon_cfgs(3);
1682 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1683 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1684 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1685 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1686 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1689 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1690 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1691 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1692 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1694 // Add a 2* and +1 for the fee spike reserve.
1695 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1696 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;
1697 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1699 // Add a pending HTLC.
1700 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1701 let payment_event_1 = {
1702 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1703 check_added_monitors!(nodes[0], 1);
1705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706 assert_eq!(events.len(), 1);
1707 SendEvent::from_event(events.remove(0))
1709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1711 // Attempt to trigger a channel reserve violation --> payment failure.
1712 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1713 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;
1714 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1715 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1717 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1718 let secp_ctx = Secp256k1::new();
1719 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1720 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1721 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1722 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1723 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1724 let msg = msgs::UpdateAddHTLC {
1727 amount_msat: htlc_msat + 1,
1728 payment_hash: our_payment_hash_1,
1729 cltv_expiry: htlc_cltv,
1730 onion_routing_packet: onion_packet,
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1734 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1735 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1736 assert_eq!(nodes[1].node.list_channels().len(), 1);
1737 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1738 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1739 check_added_monitors!(nodes[1], 1);
1740 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1744 fn test_inbound_outbound_capacity_is_not_zero() {
1745 let chanmon_cfgs = create_chanmon_cfgs(2);
1746 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1747 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1748 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1749 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1750 let channels0 = node_chanmgrs[0].list_channels();
1751 let channels1 = node_chanmgrs[1].list_channels();
1752 let default_config = UserConfig::default();
1753 assert_eq!(channels0.len(), 1);
1754 assert_eq!(channels1.len(), 1);
1756 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1757 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1758 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1760 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1761 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1764 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1765 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1769 fn test_channel_reserve_holding_cell_htlcs() {
1770 let chanmon_cfgs = create_chanmon_cfgs(3);
1771 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1772 // When this test was written, the default base fee floated based on the HTLC count.
1773 // It is now fixed, so we simply set the fee to the expected value here.
1774 let mut config = test_default_channel_config();
1775 config.channel_config.forwarding_fee_base_msat = 239;
1776 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1777 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1778 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1779 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1781 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1782 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1784 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1785 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1787 macro_rules! expect_forward {
1789 let mut events = $node.node.get_and_clear_pending_msg_events();
1790 assert_eq!(events.len(), 1);
1791 check_added_monitors!($node, 1);
1792 let payment_event = SendEvent::from_event(events.remove(0));
1797 let feemsat = 239; // set above
1798 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1799 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1800 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1802 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1804 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1806 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1807 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1808 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);
1809 route.paths[0].last_mut().unwrap().fee_msat += 1;
1810 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1812 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 },
1813 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)));
1814 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1815 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);
1818 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1819 // nodes[0]'s wealth
1821 let amt_msat = recv_value_0 + total_fee_msat;
1822 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1823 // Also, ensure that each payment has enough to be over the dust limit to
1824 // ensure it'll be included in each commit tx fee calculation.
1825 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1826 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1827 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1831 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1832 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1833 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1834 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1835 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1837 let (stat01_, stat11_, stat12_, stat22_) = (
1838 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1839 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1840 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1841 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1844 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1845 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1846 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1847 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1848 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1851 // adding pending output.
1852 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1853 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1854 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1855 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1856 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1857 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1858 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1859 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1860 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1862 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1863 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1864 let amt_msat_1 = recv_value_1 + total_fee_msat;
1866 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);
1867 let payment_event_1 = {
1868 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1869 check_added_monitors!(nodes[0], 1);
1871 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1872 assert_eq!(events.len(), 1);
1873 SendEvent::from_event(events.remove(0))
1875 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1877 // channel reserve test with htlc pending output > 0
1878 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1880 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1881 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 },
1882 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1883 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1886 // split the rest to test holding cell
1887 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1888 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1889 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1890 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1892 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1893 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);
1896 // now see if they go through on both sides
1897 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);
1898 // but this will stuck in the holding cell
1899 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1900 check_added_monitors!(nodes[0], 0);
1901 let events = nodes[0].node.get_and_clear_pending_events();
1902 assert_eq!(events.len(), 0);
1904 // test with outbound holding cell amount > 0
1906 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1907 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 },
1908 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1909 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1913 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);
1914 // this will also stuck in the holding cell
1915 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1916 check_added_monitors!(nodes[0], 0);
1917 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1918 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1920 // flush the pending htlc
1921 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1922 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1923 check_added_monitors!(nodes[1], 1);
1925 // the pending htlc should be promoted to committed
1926 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1927 check_added_monitors!(nodes[0], 1);
1928 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1930 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1931 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1932 // No commitment_signed so get_event_msg's assert(len == 1) passes
1933 check_added_monitors!(nodes[0], 1);
1935 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1936 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1937 check_added_monitors!(nodes[1], 1);
1939 expect_pending_htlcs_forwardable!(nodes[1]);
1941 let ref payment_event_11 = expect_forward!(nodes[1]);
1942 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1943 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1945 expect_pending_htlcs_forwardable!(nodes[2]);
1946 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1948 // flush the htlcs in the holding cell
1949 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1951 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1952 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1953 expect_pending_htlcs_forwardable!(nodes[1]);
1955 let ref payment_event_3 = expect_forward!(nodes[1]);
1956 assert_eq!(payment_event_3.msgs.len(), 2);
1957 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1958 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1960 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1961 expect_pending_htlcs_forwardable!(nodes[2]);
1963 let events = nodes[2].node.get_and_clear_pending_events();
1964 assert_eq!(events.len(), 2);
1966 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1967 assert_eq!(our_payment_hash_21, *payment_hash);
1968 assert_eq!(recv_value_21, amount_msat);
1969 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1970 assert_eq!(via_channel_id, Some(chan_2.2));
1972 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1973 assert!(payment_preimage.is_none());
1974 assert_eq!(our_payment_secret_21, *payment_secret);
1976 _ => panic!("expected PaymentPurpose::InvoicePayment")
1979 _ => panic!("Unexpected event"),
1982 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1983 assert_eq!(our_payment_hash_22, *payment_hash);
1984 assert_eq!(recv_value_22, amount_msat);
1985 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1986 assert_eq!(via_channel_id, Some(chan_2.2));
1988 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1989 assert!(payment_preimage.is_none());
1990 assert_eq!(our_payment_secret_22, *payment_secret);
1992 _ => panic!("expected PaymentPurpose::InvoicePayment")
1995 _ => panic!("Unexpected event"),
1998 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1999 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2000 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2002 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2003 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2004 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2006 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2007 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);
2008 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2009 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2010 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2012 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2013 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2017 fn channel_reserve_in_flight_removes() {
2018 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2019 // can send to its counterparty, but due to update ordering, the other side may not yet have
2020 // considered those HTLCs fully removed.
2021 // This tests that we don't count HTLCs which will not be included in the next remote
2022 // commitment transaction towards the reserve value (as it implies no commitment transaction
2023 // will be generated which violates the remote reserve value).
2024 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2026 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2027 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2028 // you only consider the value of the first HTLC, it may not),
2029 // * start routing a third HTLC from A to B,
2030 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2031 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2032 // * deliver the first fulfill from B
2033 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2035 // * deliver A's response CS and RAA.
2036 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2037 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2038 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2039 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2040 let chanmon_cfgs = create_chanmon_cfgs(2);
2041 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2042 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2043 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2044 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2046 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2047 // Route the first two HTLCs.
2048 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2049 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2050 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2052 // Start routing the third HTLC (this is just used to get everyone in the right state).
2053 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2055 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2056 check_added_monitors!(nodes[0], 1);
2057 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2058 assert_eq!(events.len(), 1);
2059 SendEvent::from_event(events.remove(0))
2062 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2063 // initial fulfill/CS.
2064 nodes[1].node.claim_funds(payment_preimage_1);
2065 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2066 check_added_monitors!(nodes[1], 1);
2067 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2069 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2070 // remove the second HTLC when we send the HTLC back from B to A.
2071 nodes[1].node.claim_funds(payment_preimage_2);
2072 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2073 check_added_monitors!(nodes[1], 1);
2074 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2076 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2077 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2078 check_added_monitors!(nodes[0], 1);
2079 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2082 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2083 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2084 check_added_monitors!(nodes[1], 1);
2085 // B is already AwaitingRAA, so cant generate a CS here
2086 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2088 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2089 check_added_monitors!(nodes[1], 1);
2090 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2092 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2093 check_added_monitors!(nodes[0], 1);
2094 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2096 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2097 check_added_monitors!(nodes[1], 1);
2098 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2100 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2101 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2102 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2103 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2104 // on-chain as necessary).
2105 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2107 check_added_monitors!(nodes[0], 1);
2108 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2109 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2111 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2112 check_added_monitors!(nodes[1], 1);
2113 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2115 expect_pending_htlcs_forwardable!(nodes[1]);
2116 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2118 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2119 // resolve the second HTLC from A's point of view.
2120 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2121 check_added_monitors!(nodes[0], 1);
2122 expect_payment_path_successful!(nodes[0]);
2123 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2125 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2126 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2127 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2129 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2130 check_added_monitors!(nodes[1], 1);
2131 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2132 assert_eq!(events.len(), 1);
2133 SendEvent::from_event(events.remove(0))
2136 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2137 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2138 check_added_monitors!(nodes[0], 1);
2139 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2141 // Now just resolve all the outstanding messages/HTLCs for completeness...
2143 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2144 check_added_monitors!(nodes[1], 1);
2145 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2147 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2148 check_added_monitors!(nodes[1], 1);
2150 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2151 check_added_monitors!(nodes[0], 1);
2152 expect_payment_path_successful!(nodes[0]);
2153 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2155 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2156 check_added_monitors!(nodes[1], 1);
2157 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2159 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2160 check_added_monitors!(nodes[0], 1);
2162 expect_pending_htlcs_forwardable!(nodes[0]);
2163 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2165 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2166 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2170 fn channel_monitor_network_test() {
2171 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2172 // tests that ChannelMonitor is able to recover from various states.
2173 let chanmon_cfgs = create_chanmon_cfgs(5);
2174 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2175 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2176 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2178 // Create some initial channels
2179 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2180 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2181 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2182 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2184 // Make sure all nodes are at the same starting height
2185 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2186 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2187 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2188 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2189 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2191 // Rebalance the network a bit by relaying one payment through all the channels...
2192 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2195 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2197 // Simple case with no pending HTLCs:
2198 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2199 check_added_monitors!(nodes[1], 1);
2200 check_closed_broadcast!(nodes[1], true);
2202 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2203 assert_eq!(node_txn.len(), 1);
2204 mine_transaction(&nodes[0], &node_txn[0]);
2205 check_added_monitors!(nodes[0], 1);
2206 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2208 check_closed_broadcast!(nodes[0], true);
2209 assert_eq!(nodes[0].node.list_channels().len(), 0);
2210 assert_eq!(nodes[1].node.list_channels().len(), 1);
2211 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2212 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2214 // One pending HTLC is discarded by the force-close:
2215 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2217 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2218 // broadcasted until we reach the timelock time).
2219 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2220 check_closed_broadcast!(nodes[1], true);
2221 check_added_monitors!(nodes[1], 1);
2223 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2224 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2225 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2226 mine_transaction(&nodes[2], &node_txn[0]);
2227 check_added_monitors!(nodes[2], 1);
2228 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2230 check_closed_broadcast!(nodes[2], true);
2231 assert_eq!(nodes[1].node.list_channels().len(), 0);
2232 assert_eq!(nodes[2].node.list_channels().len(), 1);
2233 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2234 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2236 macro_rules! claim_funds {
2237 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2239 $node.node.claim_funds($preimage);
2240 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2241 check_added_monitors!($node, 1);
2243 let events = $node.node.get_and_clear_pending_msg_events();
2244 assert_eq!(events.len(), 1);
2246 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2247 assert!(update_add_htlcs.is_empty());
2248 assert!(update_fail_htlcs.is_empty());
2249 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2251 _ => panic!("Unexpected event"),
2257 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2258 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2259 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2260 check_added_monitors!(nodes[2], 1);
2261 check_closed_broadcast!(nodes[2], true);
2262 let node2_commitment_txid;
2264 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2265 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2266 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2267 node2_commitment_txid = node_txn[0].txid();
2269 // Claim the payment on nodes[3], giving it knowledge of the preimage
2270 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2271 mine_transaction(&nodes[3], &node_txn[0]);
2272 check_added_monitors!(nodes[3], 1);
2273 check_preimage_claim(&nodes[3], &node_txn);
2275 check_closed_broadcast!(nodes[3], true);
2276 assert_eq!(nodes[2].node.list_channels().len(), 0);
2277 assert_eq!(nodes[3].node.list_channels().len(), 1);
2278 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2279 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2281 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2282 // confusing us in the following tests.
2283 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2285 // One pending HTLC to time out:
2286 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2287 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2290 let (close_chan_update_1, close_chan_update_2) = {
2291 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2292 let events = nodes[3].node.get_and_clear_pending_msg_events();
2293 assert_eq!(events.len(), 2);
2294 let close_chan_update_1 = match events[0] {
2295 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2298 _ => panic!("Unexpected event"),
2301 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2302 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2304 _ => panic!("Unexpected event"),
2306 check_added_monitors!(nodes[3], 1);
2308 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2310 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2311 node_txn.retain(|tx| {
2312 if tx.input[0].previous_output.txid == node2_commitment_txid {
2318 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2320 // Claim the payment on nodes[4], giving it knowledge of the preimage
2321 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2323 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2324 let events = nodes[4].node.get_and_clear_pending_msg_events();
2325 assert_eq!(events.len(), 2);
2326 let close_chan_update_2 = match events[0] {
2327 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2330 _ => panic!("Unexpected event"),
2333 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2334 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2336 _ => panic!("Unexpected event"),
2338 check_added_monitors!(nodes[4], 1);
2339 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2341 mine_transaction(&nodes[4], &node_txn[0]);
2342 check_preimage_claim(&nodes[4], &node_txn);
2343 (close_chan_update_1, close_chan_update_2)
2345 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2346 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2347 assert_eq!(nodes[3].node.list_channels().len(), 0);
2348 assert_eq!(nodes[4].node.list_channels().len(), 0);
2350 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2351 ChannelMonitorUpdateStatus::Completed);
2352 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2353 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2357 fn test_justice_tx() {
2358 // Test justice txn built on revoked HTLC-Success tx, against both sides
2359 let mut alice_config = UserConfig::default();
2360 alice_config.channel_handshake_config.announced_channel = true;
2361 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2362 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2363 let mut bob_config = UserConfig::default();
2364 bob_config.channel_handshake_config.announced_channel = true;
2365 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2366 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2367 let user_cfgs = [Some(alice_config), Some(bob_config)];
2368 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2369 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2370 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2374 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2375 // Create some new channels:
2376 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2378 // A pending HTLC which will be revoked:
2379 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2380 // Get the will-be-revoked local txn from nodes[0]
2381 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2382 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2383 assert_eq!(revoked_local_txn[0].input.len(), 1);
2384 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2385 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2386 assert_eq!(revoked_local_txn[1].input.len(), 1);
2387 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2388 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2389 // Revoke the old state
2390 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2393 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2395 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2396 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2397 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2399 check_spends!(node_txn[0], revoked_local_txn[0]);
2400 node_txn.swap_remove(0);
2402 check_added_monitors!(nodes[1], 1);
2403 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2404 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2406 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2407 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2408 // Verify broadcast of revoked HTLC-timeout
2409 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2410 check_added_monitors!(nodes[0], 1);
2411 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2412 // Broadcast revoked HTLC-timeout on node 1
2413 mine_transaction(&nodes[1], &node_txn[1]);
2414 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2416 get_announce_close_broadcast_events(&nodes, 0, 1);
2418 assert_eq!(nodes[0].node.list_channels().len(), 0);
2419 assert_eq!(nodes[1].node.list_channels().len(), 0);
2421 // We test justice_tx build by A on B's revoked HTLC-Success tx
2422 // Create some new channels:
2423 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2425 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 // A pending HTLC which will be revoked:
2430 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2431 // Get the will-be-revoked local txn from B
2432 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2433 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2434 assert_eq!(revoked_local_txn[0].input.len(), 1);
2435 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2436 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2437 // Revoke the old state
2438 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2440 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2442 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2444 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2446 check_spends!(node_txn[0], revoked_local_txn[0]);
2447 node_txn.swap_remove(0);
2449 check_added_monitors!(nodes[0], 1);
2450 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2452 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2453 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2454 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2455 check_added_monitors!(nodes[1], 1);
2456 mine_transaction(&nodes[0], &node_txn[1]);
2457 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2458 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2460 get_announce_close_broadcast_events(&nodes, 0, 1);
2461 assert_eq!(nodes[0].node.list_channels().len(), 0);
2462 assert_eq!(nodes[1].node.list_channels().len(), 0);
2466 fn revoked_output_claim() {
2467 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2468 // transaction is broadcast by its counterparty
2469 let chanmon_cfgs = create_chanmon_cfgs(2);
2470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2472 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2473 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2474 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2475 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2476 assert_eq!(revoked_local_txn.len(), 1);
2477 // Only output is the full channel value back to nodes[0]:
2478 assert_eq!(revoked_local_txn[0].output.len(), 1);
2479 // Send a payment through, updating everyone's latest commitment txn
2480 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2482 // Inform nodes[1] that nodes[0] broadcast a stale tx
2483 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2484 check_added_monitors!(nodes[1], 1);
2485 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2487 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2489 check_spends!(node_txn[0], revoked_local_txn[0]);
2491 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2492 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2493 get_announce_close_broadcast_events(&nodes, 0, 1);
2494 check_added_monitors!(nodes[0], 1);
2495 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2499 fn claim_htlc_outputs_shared_tx() {
2500 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2501 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2502 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2507 // Create some new channel:
2508 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2510 // Rebalance the network to generate htlc in the two directions
2511 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2512 // 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
2513 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2514 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2516 // Get the will-be-revoked local txn from node[0]
2517 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2518 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2519 assert_eq!(revoked_local_txn[0].input.len(), 1);
2520 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2521 assert_eq!(revoked_local_txn[1].input.len(), 1);
2522 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2523 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2524 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2526 //Revoke the old state
2527 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2530 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2531 check_added_monitors!(nodes[0], 1);
2532 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2533 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2534 check_added_monitors!(nodes[1], 1);
2535 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2536 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2537 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2539 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2540 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2542 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2543 check_spends!(node_txn[0], revoked_local_txn[0]);
2545 let mut witness_lens = BTreeSet::new();
2546 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2547 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2548 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2549 assert_eq!(witness_lens.len(), 3);
2550 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2551 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2552 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2554 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2555 // ANTI_REORG_DELAY confirmations.
2556 mine_transaction(&nodes[1], &node_txn[0]);
2557 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2558 expect_payment_failed!(nodes[1], payment_hash_2, false);
2560 get_announce_close_broadcast_events(&nodes, 0, 1);
2561 assert_eq!(nodes[0].node.list_channels().len(), 0);
2562 assert_eq!(nodes[1].node.list_channels().len(), 0);
2566 fn claim_htlc_outputs_single_tx() {
2567 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2568 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2569 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2572 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2574 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2576 // Rebalance the network to generate htlc in the two directions
2577 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2578 // 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
2579 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2580 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2581 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2583 // Get the will-be-revoked local txn from node[0]
2584 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2586 //Revoke the old state
2587 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2590 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2591 check_added_monitors!(nodes[0], 1);
2592 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2593 check_added_monitors!(nodes[1], 1);
2594 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2595 let mut events = nodes[0].node.get_and_clear_pending_events();
2596 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2597 match events.last().unwrap() {
2598 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2599 _ => panic!("Unexpected event"),
2602 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2605 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2606 assert_eq!(node_txn.len(), 7);
2608 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2609 assert_eq!(node_txn[0].input.len(), 1);
2610 check_spends!(node_txn[0], chan_1.3);
2611 assert_eq!(node_txn[1].input.len(), 1);
2612 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2613 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2614 check_spends!(node_txn[1], node_txn[0]);
2616 // Justice transactions are indices 2-3-4
2617 assert_eq!(node_txn[2].input.len(), 1);
2618 assert_eq!(node_txn[3].input.len(), 1);
2619 assert_eq!(node_txn[4].input.len(), 1);
2621 check_spends!(node_txn[2], revoked_local_txn[0]);
2622 check_spends!(node_txn[3], revoked_local_txn[0]);
2623 check_spends!(node_txn[4], revoked_local_txn[0]);
2625 let mut witness_lens = BTreeSet::new();
2626 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2627 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2628 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2629 assert_eq!(witness_lens.len(), 3);
2630 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2631 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2632 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2634 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2635 // ANTI_REORG_DELAY confirmations.
2636 mine_transaction(&nodes[1], &node_txn[2]);
2637 mine_transaction(&nodes[1], &node_txn[3]);
2638 mine_transaction(&nodes[1], &node_txn[4]);
2639 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2640 expect_payment_failed!(nodes[1], payment_hash_2, false);
2642 get_announce_close_broadcast_events(&nodes, 0, 1);
2643 assert_eq!(nodes[0].node.list_channels().len(), 0);
2644 assert_eq!(nodes[1].node.list_channels().len(), 0);
2648 fn test_htlc_on_chain_success() {
2649 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2650 // the preimage backward accordingly. So here we test that ChannelManager is
2651 // broadcasting the right event to other nodes in payment path.
2652 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2653 // A --------------------> B ----------------------> C (preimage)
2654 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2655 // commitment transaction was broadcast.
2656 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2658 // B should be able to claim via preimage if A then broadcasts its local tx.
2659 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2660 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2661 // PaymentSent event).
2663 let chanmon_cfgs = create_chanmon_cfgs(3);
2664 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2665 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2666 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2668 // Create some initial channels
2669 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2670 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2672 // Ensure all nodes are at the same height
2673 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2674 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2675 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2676 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2678 // Rebalance the network a bit by relaying one payment through all the channels...
2679 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2680 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2682 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2683 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2685 // Broadcast legit commitment tx from C on B's chain
2686 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2687 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2688 assert_eq!(commitment_tx.len(), 1);
2689 check_spends!(commitment_tx[0], chan_2.3);
2690 nodes[2].node.claim_funds(our_payment_preimage);
2691 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2692 nodes[2].node.claim_funds(our_payment_preimage_2);
2693 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2694 check_added_monitors!(nodes[2], 2);
2695 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2696 assert!(updates.update_add_htlcs.is_empty());
2697 assert!(updates.update_fail_htlcs.is_empty());
2698 assert!(updates.update_fail_malformed_htlcs.is_empty());
2699 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2701 mine_transaction(&nodes[2], &commitment_tx[0]);
2702 check_closed_broadcast!(nodes[2], true);
2703 check_added_monitors!(nodes[2], 1);
2704 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2705 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2706 assert_eq!(node_txn.len(), 2);
2707 check_spends!(node_txn[0], commitment_tx[0]);
2708 check_spends!(node_txn[1], commitment_tx[0]);
2709 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2710 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2711 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2712 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2713 assert_eq!(node_txn[0].lock_time.0, 0);
2714 assert_eq!(node_txn[1].lock_time.0, 0);
2716 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2717 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2718 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2719 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2721 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2722 assert_eq!(added_monitors.len(), 1);
2723 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2724 added_monitors.clear();
2726 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2727 assert_eq!(forwarded_events.len(), 3);
2728 match forwarded_events[0] {
2729 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2730 _ => panic!("Unexpected event"),
2732 let chan_id = Some(chan_1.2);
2733 match forwarded_events[1] {
2734 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2735 assert_eq!(fee_earned_msat, Some(1000));
2736 assert_eq!(prev_channel_id, chan_id);
2737 assert_eq!(claim_from_onchain_tx, true);
2738 assert_eq!(next_channel_id, Some(chan_2.2));
2742 match forwarded_events[2] {
2743 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
2744 assert_eq!(fee_earned_msat, Some(1000));
2745 assert_eq!(prev_channel_id, chan_id);
2746 assert_eq!(claim_from_onchain_tx, true);
2747 assert_eq!(next_channel_id, Some(chan_2.2));
2751 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2753 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2754 assert_eq!(added_monitors.len(), 2);
2755 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2756 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2757 added_monitors.clear();
2759 assert_eq!(events.len(), 3);
2761 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2762 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2764 match nodes_2_event {
2765 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2766 _ => panic!("Unexpected event"),
2769 match nodes_0_event {
2770 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, .. } } => {
2771 assert!(update_add_htlcs.is_empty());
2772 assert!(update_fail_htlcs.is_empty());
2773 assert_eq!(update_fulfill_htlcs.len(), 1);
2774 assert!(update_fail_malformed_htlcs.is_empty());
2775 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2777 _ => panic!("Unexpected event"),
2780 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2782 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2783 _ => panic!("Unexpected event"),
2786 macro_rules! check_tx_local_broadcast {
2787 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2788 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2789 assert_eq!(node_txn.len(), 2);
2790 // Node[1]: 2 * HTLC-timeout tx
2791 // Node[0]: 2 * HTLC-timeout tx
2792 check_spends!(node_txn[0], $commitment_tx);
2793 check_spends!(node_txn[1], $commitment_tx);
2794 assert_ne!(node_txn[0].lock_time.0, 0);
2795 assert_ne!(node_txn[1].lock_time.0, 0);
2797 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2798 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2799 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2800 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2802 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2803 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2804 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2805 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2810 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2811 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2813 // Broadcast legit commitment tx from A on B's chain
2814 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2815 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2816 check_spends!(node_a_commitment_tx[0], chan_1.3);
2817 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2818 check_closed_broadcast!(nodes[1], true);
2819 check_added_monitors!(nodes[1], 1);
2820 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2821 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2822 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2823 let commitment_spend =
2824 if node_txn.len() == 1 {
2827 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2828 // FullBlockViaListen
2829 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2830 check_spends!(node_txn[1], commitment_tx[0]);
2831 check_spends!(node_txn[2], commitment_tx[0]);
2832 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2835 check_spends!(node_txn[0], commitment_tx[0]);
2836 check_spends!(node_txn[1], commitment_tx[0]);
2837 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2842 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2843 assert_eq!(commitment_spend.input.len(), 2);
2844 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2845 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2846 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2847 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2848 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2849 // we already checked the same situation with A.
2851 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2852 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2853 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2854 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2855 check_closed_broadcast!(nodes[0], true);
2856 check_added_monitors!(nodes[0], 1);
2857 let events = nodes[0].node.get_and_clear_pending_events();
2858 assert_eq!(events.len(), 5);
2859 let mut first_claimed = false;
2860 for event in events {
2862 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2863 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2864 assert!(!first_claimed);
2865 first_claimed = true;
2867 assert_eq!(payment_preimage, our_payment_preimage_2);
2868 assert_eq!(payment_hash, payment_hash_2);
2871 Event::PaymentPathSuccessful { .. } => {},
2872 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2873 _ => panic!("Unexpected event"),
2876 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2879 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2880 // Test that in case of a unilateral close onchain, we detect the state of output and
2881 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2882 // broadcasting the right event to other nodes in payment path.
2883 // A ------------------> B ----------------------> C (timeout)
2884 // B's commitment tx C's commitment tx
2886 // B's HTLC timeout tx B's timeout tx
2888 let chanmon_cfgs = create_chanmon_cfgs(3);
2889 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2890 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2891 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2892 *nodes[0].connect_style.borrow_mut() = connect_style;
2893 *nodes[1].connect_style.borrow_mut() = connect_style;
2894 *nodes[2].connect_style.borrow_mut() = connect_style;
2896 // Create some intial channels
2897 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2898 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2900 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2901 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2902 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2904 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2906 // Broadcast legit commitment tx from C on B's chain
2907 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2908 check_spends!(commitment_tx[0], chan_2.3);
2909 nodes[2].node.fail_htlc_backwards(&payment_hash);
2910 check_added_monitors!(nodes[2], 0);
2911 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2912 check_added_monitors!(nodes[2], 1);
2914 let events = nodes[2].node.get_and_clear_pending_msg_events();
2915 assert_eq!(events.len(), 1);
2917 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, .. } } => {
2918 assert!(update_add_htlcs.is_empty());
2919 assert!(!update_fail_htlcs.is_empty());
2920 assert!(update_fulfill_htlcs.is_empty());
2921 assert!(update_fail_malformed_htlcs.is_empty());
2922 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2924 _ => panic!("Unexpected event"),
2926 mine_transaction(&nodes[2], &commitment_tx[0]);
2927 check_closed_broadcast!(nodes[2], true);
2928 check_added_monitors!(nodes[2], 1);
2929 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2930 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2931 assert_eq!(node_txn.len(), 0);
2933 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2934 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2935 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2936 mine_transaction(&nodes[1], &commitment_tx[0]);
2937 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2940 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2941 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2943 check_spends!(node_txn[2], commitment_tx[0]);
2944 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2946 check_spends!(node_txn[0], chan_2.3);
2947 check_spends!(node_txn[1], node_txn[0]);
2948 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2949 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2951 timeout_tx = node_txn[2].clone();
2955 mine_transaction(&nodes[1], &timeout_tx);
2956 check_added_monitors!(nodes[1], 1);
2957 check_closed_broadcast!(nodes[1], true);
2959 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2961 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 }]);
2962 check_added_monitors!(nodes[1], 1);
2963 let events = nodes[1].node.get_and_clear_pending_msg_events();
2964 assert_eq!(events.len(), 1);
2966 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, .. } } => {
2967 assert!(update_add_htlcs.is_empty());
2968 assert!(!update_fail_htlcs.is_empty());
2969 assert!(update_fulfill_htlcs.is_empty());
2970 assert!(update_fail_malformed_htlcs.is_empty());
2971 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2973 _ => panic!("Unexpected event"),
2976 // Broadcast legit commitment tx from B on A's chain
2977 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2978 check_spends!(commitment_tx[0], chan_1.3);
2980 mine_transaction(&nodes[0], &commitment_tx[0]);
2981 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2983 check_closed_broadcast!(nodes[0], true);
2984 check_added_monitors!(nodes[0], 1);
2985 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2986 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
2987 assert_eq!(node_txn.len(), 1);
2988 check_spends!(node_txn[0], commitment_tx[0]);
2989 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2993 fn test_htlc_on_chain_timeout() {
2994 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2995 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2996 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3000 fn test_simple_commitment_revoked_fail_backward() {
3001 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3002 // and fail backward accordingly.
3004 let chanmon_cfgs = create_chanmon_cfgs(3);
3005 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3006 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3007 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3009 // Create some initial channels
3010 create_announced_chan_between_nodes(&nodes, 0, 1);
3011 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3013 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3014 // Get the will-be-revoked local txn from nodes[2]
3015 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3016 // Revoke the old state
3017 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3019 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3021 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3022 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3023 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3024 check_added_monitors!(nodes[1], 1);
3025 check_closed_broadcast!(nodes[1], true);
3027 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 }]);
3028 check_added_monitors!(nodes[1], 1);
3029 let events = nodes[1].node.get_and_clear_pending_msg_events();
3030 assert_eq!(events.len(), 1);
3032 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, .. } } => {
3033 assert!(update_add_htlcs.is_empty());
3034 assert_eq!(update_fail_htlcs.len(), 1);
3035 assert!(update_fulfill_htlcs.is_empty());
3036 assert!(update_fail_malformed_htlcs.is_empty());
3037 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3039 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3040 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3041 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3043 _ => panic!("Unexpected event"),
3047 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3048 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3049 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3050 // commitment transaction anymore.
3051 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3052 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3053 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3054 // technically disallowed and we should probably handle it reasonably.
3055 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3056 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3058 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3059 // commitment_signed (implying it will be in the latest remote commitment transaction).
3060 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3061 // and once they revoke the previous commitment transaction (allowing us to send a new
3062 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3063 let chanmon_cfgs = create_chanmon_cfgs(3);
3064 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3065 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3066 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3068 // Create some initial channels
3069 create_announced_chan_between_nodes(&nodes, 0, 1);
3070 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3072 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 });
3073 // Get the will-be-revoked local txn from nodes[2]
3074 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3075 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3076 // Revoke the old state
3077 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3079 let value = if use_dust {
3080 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3081 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3082 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3083 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3086 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3087 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3088 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3090 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3091 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3092 check_added_monitors!(nodes[2], 1);
3093 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3094 assert!(updates.update_add_htlcs.is_empty());
3095 assert!(updates.update_fulfill_htlcs.is_empty());
3096 assert!(updates.update_fail_malformed_htlcs.is_empty());
3097 assert_eq!(updates.update_fail_htlcs.len(), 1);
3098 assert!(updates.update_fee.is_none());
3099 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3100 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3101 // Drop the last RAA from 3 -> 2
3103 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3104 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3105 check_added_monitors!(nodes[2], 1);
3106 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3107 assert!(updates.update_add_htlcs.is_empty());
3108 assert!(updates.update_fulfill_htlcs.is_empty());
3109 assert!(updates.update_fail_malformed_htlcs.is_empty());
3110 assert_eq!(updates.update_fail_htlcs.len(), 1);
3111 assert!(updates.update_fee.is_none());
3112 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3113 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3114 check_added_monitors!(nodes[1], 1);
3115 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3116 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3117 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3118 check_added_monitors!(nodes[2], 1);
3120 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3121 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3122 check_added_monitors!(nodes[2], 1);
3123 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3124 assert!(updates.update_add_htlcs.is_empty());
3125 assert!(updates.update_fulfill_htlcs.is_empty());
3126 assert!(updates.update_fail_malformed_htlcs.is_empty());
3127 assert_eq!(updates.update_fail_htlcs.len(), 1);
3128 assert!(updates.update_fee.is_none());
3129 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3130 // At this point first_payment_hash has dropped out of the latest two commitment
3131 // transactions that nodes[1] is tracking...
3132 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3133 check_added_monitors!(nodes[1], 1);
3134 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3135 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3136 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3137 check_added_monitors!(nodes[2], 1);
3139 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3140 // on nodes[2]'s RAA.
3141 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3142 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3143 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3144 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3145 check_added_monitors!(nodes[1], 0);
3148 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3149 // One monitor for the new revocation preimage, no second on as we won't generate a new
3150 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3151 check_added_monitors!(nodes[1], 1);
3152 let events = nodes[1].node.get_and_clear_pending_events();
3153 assert_eq!(events.len(), 2);
3155 Event::PendingHTLCsForwardable { .. } => { },
3156 _ => panic!("Unexpected event"),
3159 Event::HTLCHandlingFailed { .. } => { },
3160 _ => panic!("Unexpected event"),
3162 // Deliberately don't process the pending fail-back so they all fail back at once after
3163 // block connection just like the !deliver_bs_raa case
3166 let mut failed_htlcs = HashSet::new();
3167 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3169 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3170 check_added_monitors!(nodes[1], 1);
3171 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3173 let events = nodes[1].node.get_and_clear_pending_events();
3174 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3176 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3177 _ => panic!("Unexepected event"),
3180 Event::PaymentPathFailed { ref payment_hash, .. } => {
3181 assert_eq!(*payment_hash, fourth_payment_hash);
3183 _ => panic!("Unexpected event"),
3186 Event::PaymentFailed { ref payment_hash, .. } => {
3187 assert_eq!(*payment_hash, fourth_payment_hash);
3189 _ => panic!("Unexpected event"),
3192 nodes[1].node.process_pending_htlc_forwards();
3193 check_added_monitors!(nodes[1], 1);
3195 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3196 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3199 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3200 match nodes_2_event {
3201 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, .. } } => {
3202 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3203 assert_eq!(update_add_htlcs.len(), 1);
3204 assert!(update_fulfill_htlcs.is_empty());
3205 assert!(update_fail_htlcs.is_empty());
3206 assert!(update_fail_malformed_htlcs.is_empty());
3208 _ => panic!("Unexpected event"),
3212 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3213 match nodes_2_event {
3214 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3215 assert_eq!(channel_id, chan_2.2);
3216 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3218 _ => panic!("Unexpected event"),
3221 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3222 match nodes_0_event {
3223 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, .. } } => {
3224 assert!(update_add_htlcs.is_empty());
3225 assert_eq!(update_fail_htlcs.len(), 3);
3226 assert!(update_fulfill_htlcs.is_empty());
3227 assert!(update_fail_malformed_htlcs.is_empty());
3228 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3230 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3231 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3234 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3236 let events = nodes[0].node.get_and_clear_pending_events();
3237 assert_eq!(events.len(), 6);
3239 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3240 assert!(failed_htlcs.insert(payment_hash.0));
3241 // If we delivered B's RAA we got an unknown preimage error, not something
3242 // that we should update our routing table for.
3243 if !deliver_bs_raa {
3244 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3247 _ => panic!("Unexpected event"),
3250 Event::PaymentFailed { ref payment_hash, .. } => {
3251 assert_eq!(*payment_hash, first_payment_hash);
3253 _ => panic!("Unexpected event"),
3256 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3257 assert!(failed_htlcs.insert(payment_hash.0));
3259 _ => panic!("Unexpected event"),
3262 Event::PaymentFailed { ref payment_hash, .. } => {
3263 assert_eq!(*payment_hash, second_payment_hash);
3265 _ => panic!("Unexpected event"),
3268 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3269 assert!(failed_htlcs.insert(payment_hash.0));
3271 _ => panic!("Unexpected event"),
3274 Event::PaymentFailed { ref payment_hash, .. } => {
3275 assert_eq!(*payment_hash, third_payment_hash);
3277 _ => panic!("Unexpected event"),
3280 _ => panic!("Unexpected event"),
3283 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3285 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3286 _ => panic!("Unexpected event"),
3289 assert!(failed_htlcs.contains(&first_payment_hash.0));
3290 assert!(failed_htlcs.contains(&second_payment_hash.0));
3291 assert!(failed_htlcs.contains(&third_payment_hash.0));
3295 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3296 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3297 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3298 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3299 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3303 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3304 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3305 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3306 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3307 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3311 fn fail_backward_pending_htlc_upon_channel_failure() {
3312 let chanmon_cfgs = create_chanmon_cfgs(2);
3313 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3314 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3315 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3316 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3318 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3320 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3321 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
3322 check_added_monitors!(nodes[0], 1);
3324 let payment_event = {
3325 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3326 assert_eq!(events.len(), 1);
3327 SendEvent::from_event(events.remove(0))
3329 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3330 assert_eq!(payment_event.msgs.len(), 1);
3333 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3334 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3336 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3337 check_added_monitors!(nodes[0], 0);
3339 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3342 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3344 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3346 let secp_ctx = Secp256k1::new();
3347 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3348 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3349 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3350 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3351 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3353 // Send a 0-msat update_add_htlc to fail the channel.
3354 let update_add_htlc = msgs::UpdateAddHTLC {
3360 onion_routing_packet,
3362 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3364 let events = nodes[0].node.get_and_clear_pending_events();
3365 assert_eq!(events.len(), 3);
3366 // Check that Alice fails backward the pending HTLC from the second payment.
3368 Event::PaymentPathFailed { payment_hash, .. } => {
3369 assert_eq!(payment_hash, failed_payment_hash);
3371 _ => panic!("Unexpected event"),
3374 Event::PaymentFailed { payment_hash, .. } => {
3375 assert_eq!(payment_hash, failed_payment_hash);
3377 _ => panic!("Unexpected event"),
3380 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3381 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3383 _ => panic!("Unexpected event {:?}", events[1]),
3385 check_closed_broadcast!(nodes[0], true);
3386 check_added_monitors!(nodes[0], 1);
3390 fn test_htlc_ignore_latest_remote_commitment() {
3391 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3392 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3393 let chanmon_cfgs = create_chanmon_cfgs(2);
3394 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3395 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3396 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3397 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3398 // We rely on the ability to connect a block redundantly, which isn't allowed via
3399 // `chain::Listen`, so we never run the test if we randomly get assigned that
3403 create_announced_chan_between_nodes(&nodes, 0, 1);
3405 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3406 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3407 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3408 check_closed_broadcast!(nodes[0], true);
3409 check_added_monitors!(nodes[0], 1);
3410 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3412 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3413 assert_eq!(node_txn.len(), 3);
3414 assert_eq!(node_txn[0], node_txn[1]);
3416 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3417 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3418 check_closed_broadcast!(nodes[1], true);
3419 check_added_monitors!(nodes[1], 1);
3420 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3422 // Duplicate the connect_block call since this may happen due to other listeners
3423 // registering new transactions
3424 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3428 fn test_force_close_fail_back() {
3429 // Check which HTLCs are failed-backwards on channel force-closure
3430 let chanmon_cfgs = create_chanmon_cfgs(3);
3431 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3432 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3433 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3434 create_announced_chan_between_nodes(&nodes, 0, 1);
3435 create_announced_chan_between_nodes(&nodes, 1, 2);
3437 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3439 let mut payment_event = {
3440 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3441 check_added_monitors!(nodes[0], 1);
3443 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3444 assert_eq!(events.len(), 1);
3445 SendEvent::from_event(events.remove(0))
3448 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3449 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3451 expect_pending_htlcs_forwardable!(nodes[1]);
3453 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3454 assert_eq!(events_2.len(), 1);
3455 payment_event = SendEvent::from_event(events_2.remove(0));
3456 assert_eq!(payment_event.msgs.len(), 1);
3458 check_added_monitors!(nodes[1], 1);
3459 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3460 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3461 check_added_monitors!(nodes[2], 1);
3462 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3464 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3465 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3466 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3468 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3469 check_closed_broadcast!(nodes[2], true);
3470 check_added_monitors!(nodes[2], 1);
3471 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3473 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3474 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3475 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3476 // back to nodes[1] upon timeout otherwise.
3477 assert_eq!(node_txn.len(), 1);
3481 mine_transaction(&nodes[1], &tx);
3483 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3484 check_closed_broadcast!(nodes[1], true);
3485 check_added_monitors!(nodes[1], 1);
3486 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3488 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3490 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3491 .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);
3493 mine_transaction(&nodes[2], &tx);
3494 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3495 assert_eq!(node_txn.len(), 1);
3496 assert_eq!(node_txn[0].input.len(), 1);
3497 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3498 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3499 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3501 check_spends!(node_txn[0], tx);
3505 fn test_dup_events_on_peer_disconnect() {
3506 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3507 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3508 // as we used to generate the event immediately upon receipt of the payment preimage in the
3509 // update_fulfill_htlc message.
3511 let chanmon_cfgs = create_chanmon_cfgs(2);
3512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3515 create_announced_chan_between_nodes(&nodes, 0, 1);
3517 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3519 nodes[1].node.claim_funds(payment_preimage);
3520 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3521 check_added_monitors!(nodes[1], 1);
3522 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3523 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3524 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3526 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3527 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3529 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3530 expect_payment_path_successful!(nodes[0]);
3534 fn test_peer_disconnected_before_funding_broadcasted() {
3535 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3536 // before the funding transaction has been broadcasted.
3537 let chanmon_cfgs = create_chanmon_cfgs(2);
3538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3540 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3542 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3543 // broadcasted, even though it's created by `nodes[0]`.
3544 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();
3545 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3546 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3547 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3548 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3550 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3551 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3553 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3555 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3556 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3558 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3559 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3562 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3565 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3566 // disconnected before the funding transaction was broadcasted.
3567 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3568 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3570 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3571 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3575 fn test_simple_peer_disconnect() {
3576 // Test that we can reconnect when there are no lost messages
3577 let chanmon_cfgs = create_chanmon_cfgs(3);
3578 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3579 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3580 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3581 create_announced_chan_between_nodes(&nodes, 0, 1);
3582 create_announced_chan_between_nodes(&nodes, 1, 2);
3584 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3585 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3586 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3588 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3589 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3590 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3591 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3593 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3594 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3595 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3597 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3598 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3599 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3600 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3602 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3603 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3605 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3606 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3608 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3610 let events = nodes[0].node.get_and_clear_pending_events();
3611 assert_eq!(events.len(), 4);
3613 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3614 assert_eq!(payment_preimage, payment_preimage_3);
3615 assert_eq!(payment_hash, payment_hash_3);
3617 _ => panic!("Unexpected event"),
3620 Event::PaymentPathSuccessful { .. } => {},
3621 _ => panic!("Unexpected event"),
3624 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3625 assert_eq!(payment_hash, payment_hash_5);
3626 assert!(payment_failed_permanently);
3628 _ => panic!("Unexpected event"),
3631 Event::PaymentFailed { payment_hash, .. } => {
3632 assert_eq!(payment_hash, payment_hash_5);
3634 _ => panic!("Unexpected event"),
3638 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3639 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3642 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3643 // Test that we can reconnect when in-flight HTLC updates get dropped
3644 let chanmon_cfgs = create_chanmon_cfgs(2);
3645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3647 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3649 let mut as_channel_ready = None;
3650 let channel_id = if messages_delivered == 0 {
3651 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3652 as_channel_ready = Some(channel_ready);
3653 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3654 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3655 // it before the channel_reestablish message.
3658 create_announced_chan_between_nodes(&nodes, 0, 1).2
3661 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3663 let payment_event = {
3664 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3665 check_added_monitors!(nodes[0], 1);
3667 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3668 assert_eq!(events.len(), 1);
3669 SendEvent::from_event(events.remove(0))
3671 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3673 if messages_delivered < 2 {
3674 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3677 if messages_delivered >= 3 {
3678 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3679 check_added_monitors!(nodes[1], 1);
3680 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3682 if messages_delivered >= 4 {
3683 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3684 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3685 check_added_monitors!(nodes[0], 1);
3687 if messages_delivered >= 5 {
3688 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3689 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3690 // No commitment_signed so get_event_msg's assert(len == 1) passes
3691 check_added_monitors!(nodes[0], 1);
3693 if messages_delivered >= 6 {
3694 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3695 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3696 check_added_monitors!(nodes[1], 1);
3703 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3704 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3705 if messages_delivered < 3 {
3706 if simulate_broken_lnd {
3707 // lnd has a long-standing bug where they send a channel_ready prior to a
3708 // channel_reestablish if you reconnect prior to channel_ready time.
3710 // Here we simulate that behavior, delivering a channel_ready immediately on
3711 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3712 // in `reconnect_nodes` but we currently don't fail based on that.
3714 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3715 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3717 // Even if the channel_ready messages get exchanged, as long as nothing further was
3718 // received on either side, both sides will need to resend them.
3719 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720 } else if messages_delivered == 3 {
3721 // nodes[0] still wants its RAA + commitment_signed
3722 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3723 } else if messages_delivered == 4 {
3724 // nodes[0] still wants its commitment_signed
3725 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3726 } else if messages_delivered == 5 {
3727 // nodes[1] still wants its final RAA
3728 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3729 } else if messages_delivered == 6 {
3730 // Everything was delivered...
3731 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3734 let events_1 = nodes[1].node.get_and_clear_pending_events();
3735 if messages_delivered == 0 {
3736 assert_eq!(events_1.len(), 2);
3738 Event::ChannelReady { .. } => { },
3739 _ => panic!("Unexpected event"),
3742 Event::PendingHTLCsForwardable { .. } => { },
3743 _ => panic!("Unexpected event"),
3746 assert_eq!(events_1.len(), 1);
3748 Event::PendingHTLCsForwardable { .. } => { },
3749 _ => panic!("Unexpected event"),
3753 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3754 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3755 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3757 nodes[1].node.process_pending_htlc_forwards();
3759 let events_2 = nodes[1].node.get_and_clear_pending_events();
3760 assert_eq!(events_2.len(), 1);
3762 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3763 assert_eq!(payment_hash_1, *payment_hash);
3764 assert_eq!(amount_msat, 1_000_000);
3765 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3766 assert_eq!(via_channel_id, Some(channel_id));
3768 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3769 assert!(payment_preimage.is_none());
3770 assert_eq!(payment_secret_1, *payment_secret);
3772 _ => panic!("expected PaymentPurpose::InvoicePayment")
3775 _ => panic!("Unexpected event"),
3778 nodes[1].node.claim_funds(payment_preimage_1);
3779 check_added_monitors!(nodes[1], 1);
3780 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3782 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3783 assert_eq!(events_3.len(), 1);
3784 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3785 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3786 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3787 assert!(updates.update_add_htlcs.is_empty());
3788 assert!(updates.update_fail_htlcs.is_empty());
3789 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3790 assert!(updates.update_fail_malformed_htlcs.is_empty());
3791 assert!(updates.update_fee.is_none());
3792 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3794 _ => panic!("Unexpected event"),
3797 if messages_delivered >= 1 {
3798 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3800 let events_4 = nodes[0].node.get_and_clear_pending_events();
3801 assert_eq!(events_4.len(), 1);
3803 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3804 assert_eq!(payment_preimage_1, *payment_preimage);
3805 assert_eq!(payment_hash_1, *payment_hash);
3807 _ => panic!("Unexpected event"),
3810 if messages_delivered >= 2 {
3811 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3812 check_added_monitors!(nodes[0], 1);
3813 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3815 if messages_delivered >= 3 {
3816 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3817 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3818 check_added_monitors!(nodes[1], 1);
3820 if messages_delivered >= 4 {
3821 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3822 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3823 // No commitment_signed so get_event_msg's assert(len == 1) passes
3824 check_added_monitors!(nodes[1], 1);
3826 if messages_delivered >= 5 {
3827 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3828 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3829 check_added_monitors!(nodes[0], 1);
3836 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3837 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3838 if messages_delivered < 2 {
3839 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3840 if messages_delivered < 1 {
3841 expect_payment_sent!(nodes[0], payment_preimage_1);
3843 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3845 } else if messages_delivered == 2 {
3846 // nodes[0] still wants its RAA + commitment_signed
3847 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3848 } else if messages_delivered == 3 {
3849 // nodes[0] still wants its commitment_signed
3850 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3851 } else if messages_delivered == 4 {
3852 // nodes[1] still wants its final RAA
3853 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3854 } else if messages_delivered == 5 {
3855 // Everything was delivered...
3856 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3859 if messages_delivered == 1 || messages_delivered == 2 {
3860 expect_payment_path_successful!(nodes[0]);
3862 if messages_delivered <= 5 {
3863 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3864 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3866 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3868 if messages_delivered > 2 {
3869 expect_payment_path_successful!(nodes[0]);
3872 // Channel should still work fine...
3873 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3874 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3875 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3879 fn test_drop_messages_peer_disconnect_a() {
3880 do_test_drop_messages_peer_disconnect(0, true);
3881 do_test_drop_messages_peer_disconnect(0, false);
3882 do_test_drop_messages_peer_disconnect(1, false);
3883 do_test_drop_messages_peer_disconnect(2, false);
3887 fn test_drop_messages_peer_disconnect_b() {
3888 do_test_drop_messages_peer_disconnect(3, false);
3889 do_test_drop_messages_peer_disconnect(4, false);
3890 do_test_drop_messages_peer_disconnect(5, false);
3891 do_test_drop_messages_peer_disconnect(6, false);
3895 fn test_channel_ready_without_best_block_updated() {
3896 // Previously, if we were offline when a funding transaction was locked in, and then we came
3897 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3898 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3899 // channel_ready immediately instead.
3900 let chanmon_cfgs = create_chanmon_cfgs(2);
3901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3903 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3904 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3906 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3908 let conf_height = nodes[0].best_block_info().1 + 1;
3909 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3910 let block_txn = [funding_tx];
3911 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3912 let conf_block_header = nodes[0].get_block_header(conf_height);
3913 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3915 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3916 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3917 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3921 fn test_drop_messages_peer_disconnect_dual_htlc() {
3922 // Test that we can handle reconnecting when both sides of a channel have pending
3923 // commitment_updates when we disconnect.
3924 let chanmon_cfgs = create_chanmon_cfgs(2);
3925 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3926 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3927 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3928 create_announced_chan_between_nodes(&nodes, 0, 1);
3930 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3932 // Now try to send a second payment which will fail to send
3933 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3934 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3935 check_added_monitors!(nodes[0], 1);
3937 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3938 assert_eq!(events_1.len(), 1);
3940 MessageSendEvent::UpdateHTLCs { .. } => {},
3941 _ => panic!("Unexpected event"),
3944 nodes[1].node.claim_funds(payment_preimage_1);
3945 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3946 check_added_monitors!(nodes[1], 1);
3948 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3949 assert_eq!(events_2.len(), 1);
3951 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 } } => {
3952 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3953 assert!(update_add_htlcs.is_empty());
3954 assert_eq!(update_fulfill_htlcs.len(), 1);
3955 assert!(update_fail_htlcs.is_empty());
3956 assert!(update_fail_malformed_htlcs.is_empty());
3957 assert!(update_fee.is_none());
3959 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3960 let events_3 = nodes[0].node.get_and_clear_pending_events();
3961 assert_eq!(events_3.len(), 1);
3963 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3964 assert_eq!(*payment_preimage, payment_preimage_1);
3965 assert_eq!(*payment_hash, payment_hash_1);
3967 _ => panic!("Unexpected event"),
3970 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3971 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3972 // No commitment_signed so get_event_msg's assert(len == 1) passes
3973 check_added_monitors!(nodes[0], 1);
3975 _ => panic!("Unexpected event"),
3978 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3979 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3981 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();
3982 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3983 assert_eq!(reestablish_1.len(), 1);
3984 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();
3985 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3986 assert_eq!(reestablish_2.len(), 1);
3988 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3989 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3990 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3991 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3993 assert!(as_resp.0.is_none());
3994 assert!(bs_resp.0.is_none());
3996 assert!(bs_resp.1.is_none());
3997 assert!(bs_resp.2.is_none());
3999 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4001 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4002 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4003 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4004 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4005 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4006 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4007 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4008 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4009 // No commitment_signed so get_event_msg's assert(len == 1) passes
4010 check_added_monitors!(nodes[1], 1);
4012 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4013 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4014 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4015 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4016 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4017 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4018 assert!(bs_second_commitment_signed.update_fee.is_none());
4019 check_added_monitors!(nodes[1], 1);
4021 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4022 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4023 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4024 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4025 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4026 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4027 assert!(as_commitment_signed.update_fee.is_none());
4028 check_added_monitors!(nodes[0], 1);
4030 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4031 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4032 // No commitment_signed so get_event_msg's assert(len == 1) passes
4033 check_added_monitors!(nodes[0], 1);
4035 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4036 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4037 // No commitment_signed so get_event_msg's assert(len == 1) passes
4038 check_added_monitors!(nodes[1], 1);
4040 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4041 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4042 check_added_monitors!(nodes[1], 1);
4044 expect_pending_htlcs_forwardable!(nodes[1]);
4046 let events_5 = nodes[1].node.get_and_clear_pending_events();
4047 assert_eq!(events_5.len(), 1);
4049 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4050 assert_eq!(payment_hash_2, *payment_hash);
4052 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4053 assert!(payment_preimage.is_none());
4054 assert_eq!(payment_secret_2, *payment_secret);
4056 _ => panic!("expected PaymentPurpose::InvoicePayment")
4059 _ => panic!("Unexpected event"),
4062 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4063 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4064 check_added_monitors!(nodes[0], 1);
4066 expect_payment_path_successful!(nodes[0]);
4067 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4070 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4071 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4072 // to avoid our counterparty failing the channel.
4073 let chanmon_cfgs = create_chanmon_cfgs(2);
4074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4078 create_announced_chan_between_nodes(&nodes, 0, 1);
4080 let our_payment_hash = if send_partial_mpp {
4081 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4082 // Use the utility function send_payment_along_path to send the payment with MPP data which
4083 // indicates there are more HTLCs coming.
4084 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.
4085 let payment_id = PaymentId([42; 32]);
4086 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(payment_secret), payment_id, &route).unwrap();
4087 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();
4088 check_added_monitors!(nodes[0], 1);
4089 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4090 assert_eq!(events.len(), 1);
4091 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4092 // hop should *not* yet generate any PaymentClaimable event(s).
4093 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4096 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4099 let mut block = Block {
4100 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4103 connect_block(&nodes[0], &block);
4104 connect_block(&nodes[1], &block);
4105 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4106 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4107 block.header.prev_blockhash = block.block_hash();
4108 connect_block(&nodes[0], &block);
4109 connect_block(&nodes[1], &block);
4112 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4114 check_added_monitors!(nodes[1], 1);
4115 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4116 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4117 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4118 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4119 assert!(htlc_timeout_updates.update_fee.is_none());
4121 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4122 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4123 // 100_000 msat as u64, followed by the height at which we failed back above
4124 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4125 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4126 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4130 fn test_htlc_timeout() {
4131 do_test_htlc_timeout(true);
4132 do_test_htlc_timeout(false);
4135 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4136 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4137 let chanmon_cfgs = create_chanmon_cfgs(3);
4138 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4139 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4140 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4141 create_announced_chan_between_nodes(&nodes, 0, 1);
4142 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4144 // Make sure all nodes are at the same starting height
4145 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4146 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4147 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4149 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4150 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4152 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4154 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4155 check_added_monitors!(nodes[1], 1);
4157 // Now attempt to route a second payment, which should be placed in the holding cell
4158 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4159 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4160 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4162 check_added_monitors!(nodes[0], 1);
4163 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4164 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4165 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4166 expect_pending_htlcs_forwardable!(nodes[1]);
4168 check_added_monitors!(nodes[1], 0);
4170 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4171 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4172 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4173 connect_blocks(&nodes[1], 1);
4176 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 }]);
4177 check_added_monitors!(nodes[1], 1);
4178 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4179 assert_eq!(fail_commit.len(), 1);
4180 match fail_commit[0] {
4181 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4182 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4183 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4185 _ => unreachable!(),
4187 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4189 expect_payment_failed!(nodes[1], second_payment_hash, false);
4194 fn test_holding_cell_htlc_add_timeouts() {
4195 do_test_holding_cell_htlc_add_timeouts(false);
4196 do_test_holding_cell_htlc_add_timeouts(true);
4199 macro_rules! check_spendable_outputs {
4200 ($node: expr, $keysinterface: expr) => {
4202 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4203 let mut txn = Vec::new();
4204 let mut all_outputs = Vec::new();
4205 let secp_ctx = Secp256k1::new();
4206 for event in events.drain(..) {
4208 Event::SpendableOutputs { mut outputs } => {
4209 for outp in outputs.drain(..) {
4210 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4211 all_outputs.push(outp);
4214 _ => panic!("Unexpected event"),
4217 if all_outputs.len() > 1 {
4218 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) {
4228 fn test_claim_sizeable_push_msat() {
4229 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4230 let chanmon_cfgs = create_chanmon_cfgs(2);
4231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4235 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4236 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4237 check_closed_broadcast!(nodes[1], true);
4238 check_added_monitors!(nodes[1], 1);
4239 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4240 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4241 assert_eq!(node_txn.len(), 1);
4242 check_spends!(node_txn[0], chan.3);
4243 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
4245 mine_transaction(&nodes[1], &node_txn[0]);
4246 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4248 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4249 assert_eq!(spend_txn.len(), 1);
4250 assert_eq!(spend_txn[0].input.len(), 1);
4251 check_spends!(spend_txn[0], node_txn[0]);
4252 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4256 fn test_claim_on_remote_sizeable_push_msat() {
4257 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4258 // to_remote output is encumbered by a P2WPKH
4259 let chanmon_cfgs = create_chanmon_cfgs(2);
4260 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4261 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4262 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4264 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4265 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4266 check_closed_broadcast!(nodes[0], true);
4267 check_added_monitors!(nodes[0], 1);
4268 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4270 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4271 assert_eq!(node_txn.len(), 1);
4272 check_spends!(node_txn[0], chan.3);
4273 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
4275 mine_transaction(&nodes[1], &node_txn[0]);
4276 check_closed_broadcast!(nodes[1], true);
4277 check_added_monitors!(nodes[1], 1);
4278 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4279 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4281 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4282 assert_eq!(spend_txn.len(), 1);
4283 check_spends!(spend_txn[0], node_txn[0]);
4287 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4288 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4289 // to_remote output is encumbered by a P2WPKH
4291 let chanmon_cfgs = create_chanmon_cfgs(2);
4292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4294 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4296 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4297 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4298 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4299 assert_eq!(revoked_local_txn[0].input.len(), 1);
4300 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4302 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4303 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4304 check_closed_broadcast!(nodes[1], true);
4305 check_added_monitors!(nodes[1], 1);
4306 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4308 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4309 mine_transaction(&nodes[1], &node_txn[0]);
4310 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4312 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4313 assert_eq!(spend_txn.len(), 3);
4314 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4315 check_spends!(spend_txn[1], node_txn[0]);
4316 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4320 fn test_static_spendable_outputs_preimage_tx() {
4321 let chanmon_cfgs = create_chanmon_cfgs(2);
4322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4324 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4326 // Create some initial channels
4327 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4329 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4331 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4332 assert_eq!(commitment_tx[0].input.len(), 1);
4333 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4335 // Settle A's commitment tx on B's chain
4336 nodes[1].node.claim_funds(payment_preimage);
4337 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4338 check_added_monitors!(nodes[1], 1);
4339 mine_transaction(&nodes[1], &commitment_tx[0]);
4340 check_added_monitors!(nodes[1], 1);
4341 let events = nodes[1].node.get_and_clear_pending_msg_events();
4343 MessageSendEvent::UpdateHTLCs { .. } => {},
4344 _ => panic!("Unexpected event"),
4347 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4348 _ => panic!("Unexepected event"),
4351 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4352 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4353 assert_eq!(node_txn.len(), 1);
4354 check_spends!(node_txn[0], commitment_tx[0]);
4355 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4357 mine_transaction(&nodes[1], &node_txn[0]);
4358 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4359 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4361 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4362 assert_eq!(spend_txn.len(), 1);
4363 check_spends!(spend_txn[0], node_txn[0]);
4367 fn test_static_spendable_outputs_timeout_tx() {
4368 let chanmon_cfgs = create_chanmon_cfgs(2);
4369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4371 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4373 // Create some initial channels
4374 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4376 // Rebalance the network a bit by relaying one payment through all the channels ...
4377 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4379 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4381 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4382 assert_eq!(commitment_tx[0].input.len(), 1);
4383 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4385 // Settle A's commitment tx on B' chain
4386 mine_transaction(&nodes[1], &commitment_tx[0]);
4387 check_added_monitors!(nodes[1], 1);
4388 let events = nodes[1].node.get_and_clear_pending_msg_events();
4390 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4391 _ => panic!("Unexpected event"),
4393 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4395 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4396 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4397 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4398 check_spends!(node_txn[0], commitment_tx[0].clone());
4399 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4401 mine_transaction(&nodes[1], &node_txn[0]);
4402 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4403 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4404 expect_payment_failed!(nodes[1], our_payment_hash, false);
4406 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4407 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4408 check_spends!(spend_txn[0], commitment_tx[0]);
4409 check_spends!(spend_txn[1], node_txn[0]);
4410 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4414 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4415 let chanmon_cfgs = create_chanmon_cfgs(2);
4416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4420 // Create some initial channels
4421 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4423 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4424 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4425 assert_eq!(revoked_local_txn[0].input.len(), 1);
4426 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4428 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4430 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4431 check_closed_broadcast!(nodes[1], true);
4432 check_added_monitors!(nodes[1], 1);
4433 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4435 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4436 assert_eq!(node_txn.len(), 1);
4437 assert_eq!(node_txn[0].input.len(), 2);
4438 check_spends!(node_txn[0], revoked_local_txn[0]);
4440 mine_transaction(&nodes[1], &node_txn[0]);
4441 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4443 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4444 assert_eq!(spend_txn.len(), 1);
4445 check_spends!(spend_txn[0], node_txn[0]);
4449 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4450 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4451 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4452 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4453 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4454 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4456 // Create some initial channels
4457 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4459 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4460 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4461 assert_eq!(revoked_local_txn[0].input.len(), 1);
4462 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4464 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4466 // A will generate HTLC-Timeout from revoked commitment tx
4467 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4468 check_closed_broadcast!(nodes[0], true);
4469 check_added_monitors!(nodes[0], 1);
4470 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4471 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4473 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4474 assert_eq!(revoked_htlc_txn.len(), 1);
4475 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4476 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4477 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4478 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4480 // B will generate justice tx from A's revoked commitment/HTLC tx
4481 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4482 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4483 check_closed_broadcast!(nodes[1], true);
4484 check_added_monitors!(nodes[1], 1);
4485 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4487 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4488 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4489 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4490 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4491 // transactions next...
4492 assert_eq!(node_txn[0].input.len(), 3);
4493 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4495 assert_eq!(node_txn[1].input.len(), 2);
4496 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4497 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4498 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4500 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4501 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4504 mine_transaction(&nodes[1], &node_txn[1]);
4505 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4507 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4508 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4509 assert_eq!(spend_txn.len(), 1);
4510 assert_eq!(spend_txn[0].input.len(), 1);
4511 check_spends!(spend_txn[0], node_txn[1]);
4515 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4516 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4517 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4520 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4522 // Create some initial channels
4523 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4525 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4526 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4527 assert_eq!(revoked_local_txn[0].input.len(), 1);
4528 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4530 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4531 assert_eq!(revoked_local_txn[0].output.len(), 2);
4533 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4535 // B will generate HTLC-Success from revoked commitment tx
4536 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4537 check_closed_broadcast!(nodes[1], true);
4538 check_added_monitors!(nodes[1], 1);
4539 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4540 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4542 assert_eq!(revoked_htlc_txn.len(), 1);
4543 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4544 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4545 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4547 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4548 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4549 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4551 // A will generate justice tx from B's revoked commitment/HTLC tx
4552 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4553 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4554 check_closed_broadcast!(nodes[0], true);
4555 check_added_monitors!(nodes[0], 1);
4556 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4558 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4559 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4561 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4562 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4563 // transactions next...
4564 assert_eq!(node_txn[0].input.len(), 2);
4565 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4566 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4567 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4569 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4570 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4573 assert_eq!(node_txn[1].input.len(), 1);
4574 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4576 mine_transaction(&nodes[0], &node_txn[1]);
4577 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4579 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4580 // didn't try to generate any new transactions.
4582 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4583 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4584 assert_eq!(spend_txn.len(), 3);
4585 assert_eq!(spend_txn[0].input.len(), 1);
4586 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4587 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4588 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4589 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4593 fn test_onchain_to_onchain_claim() {
4594 // Test that in case of channel closure, we detect the state of output and claim HTLC
4595 // on downstream peer's remote commitment tx.
4596 // First, have C claim an HTLC against its own latest commitment transaction.
4597 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4599 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4602 let chanmon_cfgs = create_chanmon_cfgs(3);
4603 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4604 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4605 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4607 // Create some initial channels
4608 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4609 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4611 // Ensure all nodes are at the same height
4612 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4613 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4614 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4615 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4617 // Rebalance the network a bit by relaying one payment through all the channels ...
4618 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4619 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4621 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4622 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4623 check_spends!(commitment_tx[0], chan_2.3);
4624 nodes[2].node.claim_funds(payment_preimage);
4625 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4626 check_added_monitors!(nodes[2], 1);
4627 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4628 assert!(updates.update_add_htlcs.is_empty());
4629 assert!(updates.update_fail_htlcs.is_empty());
4630 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4631 assert!(updates.update_fail_malformed_htlcs.is_empty());
4633 mine_transaction(&nodes[2], &commitment_tx[0]);
4634 check_closed_broadcast!(nodes[2], true);
4635 check_added_monitors!(nodes[2], 1);
4636 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4638 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4639 assert_eq!(c_txn.len(), 1);
4640 check_spends!(c_txn[0], commitment_tx[0]);
4641 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4642 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4643 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4645 // 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
4646 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4647 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4648 check_added_monitors!(nodes[1], 1);
4649 let events = nodes[1].node.get_and_clear_pending_events();
4650 assert_eq!(events.len(), 2);
4652 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4653 _ => panic!("Unexpected event"),
4656 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id } => {
4657 assert_eq!(fee_earned_msat, Some(1000));
4658 assert_eq!(prev_channel_id, Some(chan_1.2));
4659 assert_eq!(claim_from_onchain_tx, true);
4660 assert_eq!(next_channel_id, Some(chan_2.2));
4662 _ => panic!("Unexpected event"),
4664 check_added_monitors!(nodes[1], 1);
4665 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4666 assert_eq!(msg_events.len(), 3);
4667 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4668 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4670 match nodes_2_event {
4671 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4672 _ => panic!("Unexpected event"),
4675 match nodes_0_event {
4676 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, .. } } => {
4677 assert!(update_add_htlcs.is_empty());
4678 assert!(update_fail_htlcs.is_empty());
4679 assert_eq!(update_fulfill_htlcs.len(), 1);
4680 assert!(update_fail_malformed_htlcs.is_empty());
4681 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4683 _ => panic!("Unexpected event"),
4686 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4687 match msg_events[0] {
4688 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4689 _ => panic!("Unexpected event"),
4692 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4693 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4694 mine_transaction(&nodes[1], &commitment_tx[0]);
4695 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4696 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4697 // ChannelMonitor: HTLC-Success tx
4698 assert_eq!(b_txn.len(), 1);
4699 check_spends!(b_txn[0], commitment_tx[0]);
4700 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4701 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4702 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4704 check_closed_broadcast!(nodes[1], true);
4705 check_added_monitors!(nodes[1], 1);
4709 fn test_duplicate_payment_hash_one_failure_one_success() {
4710 // Topology : A --> B --> C --> D
4711 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4712 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4713 // we forward one of the payments onwards to D.
4714 let chanmon_cfgs = create_chanmon_cfgs(4);
4715 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4716 // When this test was written, the default base fee floated based on the HTLC count.
4717 // It is now fixed, so we simply set the fee to the expected value here.
4718 let mut config = test_default_channel_config();
4719 config.channel_config.forwarding_fee_base_msat = 196;
4720 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4721 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4722 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4724 create_announced_chan_between_nodes(&nodes, 0, 1);
4725 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4726 create_announced_chan_between_nodes(&nodes, 2, 3);
4728 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4729 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4730 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4731 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4732 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4734 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4736 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4737 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4738 // script push size limit so that the below script length checks match
4739 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4740 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4741 .with_features(nodes[3].node.invoice_features());
4742 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4743 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4745 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4746 assert_eq!(commitment_txn[0].input.len(), 1);
4747 check_spends!(commitment_txn[0], chan_2.3);
4749 mine_transaction(&nodes[1], &commitment_txn[0]);
4750 check_closed_broadcast!(nodes[1], true);
4751 check_added_monitors!(nodes[1], 1);
4752 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4753 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4755 let htlc_timeout_tx;
4756 { // Extract one of the two HTLC-Timeout transaction
4757 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4758 // ChannelMonitor: timeout tx * 2-or-3
4759 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4761 check_spends!(node_txn[0], commitment_txn[0]);
4762 assert_eq!(node_txn[0].input.len(), 1);
4763 assert_eq!(node_txn[0].output.len(), 1);
4765 if node_txn.len() > 2 {
4766 check_spends!(node_txn[1], commitment_txn[0]);
4767 assert_eq!(node_txn[1].input.len(), 1);
4768 assert_eq!(node_txn[1].output.len(), 1);
4769 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4771 check_spends!(node_txn[2], commitment_txn[0]);
4772 assert_eq!(node_txn[2].input.len(), 1);
4773 assert_eq!(node_txn[2].output.len(), 1);
4774 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4776 check_spends!(node_txn[1], commitment_txn[0]);
4777 assert_eq!(node_txn[1].input.len(), 1);
4778 assert_eq!(node_txn[1].output.len(), 1);
4779 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4782 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4783 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4784 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4785 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4786 if node_txn.len() > 2 {
4787 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4788 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4790 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4794 nodes[2].node.claim_funds(our_payment_preimage);
4795 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4797 mine_transaction(&nodes[2], &commitment_txn[0]);
4798 check_added_monitors!(nodes[2], 2);
4799 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4800 let events = nodes[2].node.get_and_clear_pending_msg_events();
4802 MessageSendEvent::UpdateHTLCs { .. } => {},
4803 _ => panic!("Unexpected event"),
4806 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4807 _ => panic!("Unexepected event"),
4809 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4810 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4811 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4812 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4813 assert_eq!(htlc_success_txn[0].input.len(), 1);
4814 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4815 assert_eq!(htlc_success_txn[1].input.len(), 1);
4816 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4817 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4818 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4820 mine_transaction(&nodes[1], &htlc_timeout_tx);
4821 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4822 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 }]);
4823 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4824 assert!(htlc_updates.update_add_htlcs.is_empty());
4825 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4826 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4827 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4828 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4829 check_added_monitors!(nodes[1], 1);
4831 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4832 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4834 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4836 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4838 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4839 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4840 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4841 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4842 assert!(updates.update_add_htlcs.is_empty());
4843 assert!(updates.update_fail_htlcs.is_empty());
4844 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4845 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4846 assert!(updates.update_fail_malformed_htlcs.is_empty());
4847 check_added_monitors!(nodes[1], 1);
4849 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4850 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4852 let events = nodes[0].node.get_and_clear_pending_events();
4854 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4855 assert_eq!(*payment_preimage, our_payment_preimage);
4856 assert_eq!(*payment_hash, duplicate_payment_hash);
4858 _ => panic!("Unexpected event"),
4863 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4864 let chanmon_cfgs = create_chanmon_cfgs(2);
4865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4869 // Create some initial channels
4870 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4872 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4873 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4874 assert_eq!(local_txn.len(), 1);
4875 assert_eq!(local_txn[0].input.len(), 1);
4876 check_spends!(local_txn[0], chan_1.3);
4878 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4879 nodes[1].node.claim_funds(payment_preimage);
4880 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4881 check_added_monitors!(nodes[1], 1);
4883 mine_transaction(&nodes[1], &local_txn[0]);
4884 check_added_monitors!(nodes[1], 1);
4885 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4886 let events = nodes[1].node.get_and_clear_pending_msg_events();
4888 MessageSendEvent::UpdateHTLCs { .. } => {},
4889 _ => panic!("Unexpected event"),
4892 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4893 _ => panic!("Unexepected event"),
4896 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4897 assert_eq!(node_txn.len(), 1);
4898 assert_eq!(node_txn[0].input.len(), 1);
4899 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4900 check_spends!(node_txn[0], local_txn[0]);
4904 mine_transaction(&nodes[1], &node_tx);
4905 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4907 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4908 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4909 assert_eq!(spend_txn.len(), 1);
4910 assert_eq!(spend_txn[0].input.len(), 1);
4911 check_spends!(spend_txn[0], node_tx);
4912 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4915 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4916 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4917 // unrevoked commitment transaction.
4918 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4919 // a remote RAA before they could be failed backwards (and combinations thereof).
4920 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4921 // use the same payment hashes.
4922 // Thus, we use a six-node network:
4927 // And test where C fails back to A/B when D announces its latest commitment transaction
4928 let chanmon_cfgs = create_chanmon_cfgs(6);
4929 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4930 // When this test was written, the default base fee floated based on the HTLC count.
4931 // It is now fixed, so we simply set the fee to the expected value here.
4932 let mut config = test_default_channel_config();
4933 config.channel_config.forwarding_fee_base_msat = 196;
4934 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4935 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4936 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4938 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4939 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4940 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4941 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4942 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4944 // Rebalance and check output sanity...
4945 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4946 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4947 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4949 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4950 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4952 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
4954 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
4955 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4957 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
4959 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
4961 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4963 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4964 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4966 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());
4968 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());
4971 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4973 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4974 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
4977 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
4979 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
4980 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());
4982 // Double-check that six of the new HTLC were added
4983 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4984 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4985 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
4986 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
4988 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4989 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4990 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
4991 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
4992 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
4993 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
4994 check_added_monitors!(nodes[4], 0);
4996 let failed_destinations = vec![
4997 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
4998 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
4999 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5000 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5002 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5003 check_added_monitors!(nodes[4], 1);
5005 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5006 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5007 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5008 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5009 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5010 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5012 // Fail 3rd below-dust and 7th above-dust HTLCs
5013 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5014 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5015 check_added_monitors!(nodes[5], 0);
5017 let failed_destinations_2 = vec![
5018 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5019 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5021 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5022 check_added_monitors!(nodes[5], 1);
5024 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5025 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5026 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5027 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5029 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5031 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5032 let failed_destinations_3 = vec![
5033 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5034 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5035 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5036 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5037 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5038 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5040 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5041 check_added_monitors!(nodes[3], 1);
5042 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5043 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5044 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5045 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5046 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5047 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5048 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5049 if deliver_last_raa {
5050 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5052 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5055 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5056 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5057 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5058 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5060 // We now broadcast the latest commitment transaction, which *should* result in failures for
5061 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5062 // the non-broadcast above-dust HTLCs.
5064 // Alternatively, we may broadcast the previous commitment transaction, which should only
5065 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5066 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5068 if announce_latest {
5069 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5071 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5073 let events = nodes[2].node.get_and_clear_pending_events();
5074 let close_event = if deliver_last_raa {
5075 assert_eq!(events.len(), 2 + 6);
5076 events.last().clone().unwrap()
5078 assert_eq!(events.len(), 1);
5079 events.last().clone().unwrap()
5082 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5083 _ => panic!("Unexpected event"),
5086 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5087 check_closed_broadcast!(nodes[2], true);
5088 if deliver_last_raa {
5089 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5091 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();
5092 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5094 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5095 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5097 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5100 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5102 check_added_monitors!(nodes[2], 3);
5104 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5105 assert_eq!(cs_msgs.len(), 2);
5106 let mut a_done = false;
5107 for msg in cs_msgs {
5109 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5110 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5111 // should be failed-backwards here.
5112 let target = if *node_id == nodes[0].node.get_our_node_id() {
5113 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5114 for htlc in &updates.update_fail_htlcs {
5115 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 });
5117 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5122 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5123 for htlc in &updates.update_fail_htlcs {
5124 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5126 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5127 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5130 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5131 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5132 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5133 if announce_latest {
5134 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5135 if *node_id == nodes[0].node.get_our_node_id() {
5136 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5139 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5141 _ => panic!("Unexpected event"),
5145 let as_events = nodes[0].node.get_and_clear_pending_events();
5146 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5147 let mut as_failds = HashSet::new();
5148 let mut as_updates = 0;
5149 for event in as_events.iter() {
5150 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5151 assert!(as_failds.insert(*payment_hash));
5152 if *payment_hash != payment_hash_2 {
5153 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5155 assert!(!payment_failed_permanently);
5157 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5160 } else if let &Event::PaymentFailed { .. } = event {
5161 } else { panic!("Unexpected event"); }
5163 assert!(as_failds.contains(&payment_hash_1));
5164 assert!(as_failds.contains(&payment_hash_2));
5165 if announce_latest {
5166 assert!(as_failds.contains(&payment_hash_3));
5167 assert!(as_failds.contains(&payment_hash_5));
5169 assert!(as_failds.contains(&payment_hash_6));
5171 let bs_events = nodes[1].node.get_and_clear_pending_events();
5172 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5173 let mut bs_failds = HashSet::new();
5174 let mut bs_updates = 0;
5175 for event in bs_events.iter() {
5176 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5177 assert!(bs_failds.insert(*payment_hash));
5178 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5179 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5181 assert!(!payment_failed_permanently);
5183 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5186 } else if let &Event::PaymentFailed { .. } = event {
5187 } else { panic!("Unexpected event"); }
5189 assert!(bs_failds.contains(&payment_hash_1));
5190 assert!(bs_failds.contains(&payment_hash_2));
5191 if announce_latest {
5192 assert!(bs_failds.contains(&payment_hash_4));
5194 assert!(bs_failds.contains(&payment_hash_5));
5196 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5197 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5198 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5199 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5200 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5201 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5205 fn test_fail_backwards_latest_remote_announce_a() {
5206 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5210 fn test_fail_backwards_latest_remote_announce_b() {
5211 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5215 fn test_fail_backwards_previous_remote_announce() {
5216 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5217 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5218 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5222 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5223 let chanmon_cfgs = create_chanmon_cfgs(2);
5224 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5225 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5226 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5228 // Create some initial channels
5229 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5231 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5232 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5233 assert_eq!(local_txn[0].input.len(), 1);
5234 check_spends!(local_txn[0], chan_1.3);
5236 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5237 mine_transaction(&nodes[0], &local_txn[0]);
5238 check_closed_broadcast!(nodes[0], true);
5239 check_added_monitors!(nodes[0], 1);
5240 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5241 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5243 let htlc_timeout = {
5244 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5245 assert_eq!(node_txn.len(), 1);
5246 assert_eq!(node_txn[0].input.len(), 1);
5247 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5248 check_spends!(node_txn[0], local_txn[0]);
5252 mine_transaction(&nodes[0], &htlc_timeout);
5253 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5254 expect_payment_failed!(nodes[0], our_payment_hash, false);
5256 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5257 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5258 assert_eq!(spend_txn.len(), 3);
5259 check_spends!(spend_txn[0], local_txn[0]);
5260 assert_eq!(spend_txn[1].input.len(), 1);
5261 check_spends!(spend_txn[1], htlc_timeout);
5262 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5263 assert_eq!(spend_txn[2].input.len(), 2);
5264 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5265 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5266 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5270 fn test_key_derivation_params() {
5271 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5272 // manager rotation to test that `channel_keys_id` returned in
5273 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5274 // then derive a `delayed_payment_key`.
5276 let chanmon_cfgs = create_chanmon_cfgs(3);
5278 // We manually create the node configuration to backup the seed.
5279 let seed = [42; 32];
5280 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5281 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);
5282 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5283 let scorer = Mutex::new(test_utils::TestScorer::new());
5284 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5285 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)) };
5286 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5287 node_cfgs.remove(0);
5288 node_cfgs.insert(0, node);
5290 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5291 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5293 // Create some initial channels
5294 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5296 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5297 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5298 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5300 // Ensure all nodes are at the same height
5301 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5302 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5303 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5304 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5306 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5307 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5308 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5309 assert_eq!(local_txn_1[0].input.len(), 1);
5310 check_spends!(local_txn_1[0], chan_1.3);
5312 // We check funding pubkey are unique
5313 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]));
5314 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]));
5315 if from_0_funding_key_0 == from_1_funding_key_0
5316 || from_0_funding_key_0 == from_1_funding_key_1
5317 || from_0_funding_key_1 == from_1_funding_key_0
5318 || from_0_funding_key_1 == from_1_funding_key_1 {
5319 panic!("Funding pubkeys aren't unique");
5322 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5323 mine_transaction(&nodes[0], &local_txn_1[0]);
5324 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5325 check_closed_broadcast!(nodes[0], true);
5326 check_added_monitors!(nodes[0], 1);
5327 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5329 let htlc_timeout = {
5330 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5331 assert_eq!(node_txn.len(), 1);
5332 assert_eq!(node_txn[0].input.len(), 1);
5333 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5334 check_spends!(node_txn[0], local_txn_1[0]);
5338 mine_transaction(&nodes[0], &htlc_timeout);
5339 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5340 expect_payment_failed!(nodes[0], our_payment_hash, false);
5342 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5343 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5344 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5345 assert_eq!(spend_txn.len(), 3);
5346 check_spends!(spend_txn[0], local_txn_1[0]);
5347 assert_eq!(spend_txn[1].input.len(), 1);
5348 check_spends!(spend_txn[1], htlc_timeout);
5349 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5350 assert_eq!(spend_txn[2].input.len(), 2);
5351 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5352 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5353 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5357 fn test_static_output_closing_tx() {
5358 let chanmon_cfgs = create_chanmon_cfgs(2);
5359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5361 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5363 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5365 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5366 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5368 mine_transaction(&nodes[0], &closing_tx);
5369 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5370 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5372 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5373 assert_eq!(spend_txn.len(), 1);
5374 check_spends!(spend_txn[0], closing_tx);
5376 mine_transaction(&nodes[1], &closing_tx);
5377 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5378 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5380 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5381 assert_eq!(spend_txn.len(), 1);
5382 check_spends!(spend_txn[0], closing_tx);
5385 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5386 let chanmon_cfgs = create_chanmon_cfgs(2);
5387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5390 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5392 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5394 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5395 // present in B's local commitment transaction, but none of A's commitment transactions.
5396 nodes[1].node.claim_funds(payment_preimage);
5397 check_added_monitors!(nodes[1], 1);
5398 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5400 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5401 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5402 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5404 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5405 check_added_monitors!(nodes[0], 1);
5406 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5407 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5408 check_added_monitors!(nodes[1], 1);
5410 let starting_block = nodes[1].best_block_info();
5411 let mut block = Block {
5412 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5415 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5416 connect_block(&nodes[1], &block);
5417 block.header.prev_blockhash = block.block_hash();
5419 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5420 check_closed_broadcast!(nodes[1], true);
5421 check_added_monitors!(nodes[1], 1);
5422 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5425 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5426 let chanmon_cfgs = create_chanmon_cfgs(2);
5427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5430 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5432 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5433 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
5434 check_added_monitors!(nodes[0], 1);
5436 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5438 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5439 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5440 // to "time out" the HTLC.
5442 let starting_block = nodes[1].best_block_info();
5443 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5445 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5446 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5447 header.prev_blockhash = header.block_hash();
5449 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5450 check_closed_broadcast!(nodes[0], true);
5451 check_added_monitors!(nodes[0], 1);
5452 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5455 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5456 let chanmon_cfgs = create_chanmon_cfgs(3);
5457 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5458 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5459 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5460 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5462 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5463 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5464 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5465 // actually revoked.
5466 let htlc_value = if use_dust { 50000 } else { 3000000 };
5467 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5468 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5469 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5470 check_added_monitors!(nodes[1], 1);
5472 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5473 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5474 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5475 check_added_monitors!(nodes[0], 1);
5476 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5477 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5478 check_added_monitors!(nodes[1], 1);
5479 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5480 check_added_monitors!(nodes[1], 1);
5481 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5483 if check_revoke_no_close {
5484 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5485 check_added_monitors!(nodes[0], 1);
5488 let starting_block = nodes[1].best_block_info();
5489 let mut block = Block {
5490 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5493 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5494 connect_block(&nodes[0], &block);
5495 block.header.prev_blockhash = block.block_hash();
5497 if !check_revoke_no_close {
5498 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5499 check_closed_broadcast!(nodes[0], true);
5500 check_added_monitors!(nodes[0], 1);
5501 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5503 expect_payment_failed!(nodes[0], our_payment_hash, true);
5507 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5508 // There are only a few cases to test here:
5509 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5510 // broadcastable commitment transactions result in channel closure,
5511 // * its included in an unrevoked-but-previous remote commitment transaction,
5512 // * its included in the latest remote or local commitment transactions.
5513 // We test each of the three possible commitment transactions individually and use both dust and
5515 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5516 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5517 // tested for at least one of the cases in other tests.
5519 fn htlc_claim_single_commitment_only_a() {
5520 do_htlc_claim_local_commitment_only(true);
5521 do_htlc_claim_local_commitment_only(false);
5523 do_htlc_claim_current_remote_commitment_only(true);
5524 do_htlc_claim_current_remote_commitment_only(false);
5528 fn htlc_claim_single_commitment_only_b() {
5529 do_htlc_claim_previous_remote_commitment_only(true, false);
5530 do_htlc_claim_previous_remote_commitment_only(false, false);
5531 do_htlc_claim_previous_remote_commitment_only(true, true);
5532 do_htlc_claim_previous_remote_commitment_only(false, true);
5537 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5538 let chanmon_cfgs = create_chanmon_cfgs(2);
5539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5542 // Force duplicate randomness for every get-random call
5543 for node in nodes.iter() {
5544 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5547 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5548 let channel_value_satoshis=10000;
5549 let push_msat=10001;
5550 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5551 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5552 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5553 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5555 // Create a second channel with the same random values. This used to panic due to a colliding
5556 // channel_id, but now panics due to a colliding outbound SCID alias.
5557 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5561 fn bolt2_open_channel_sending_node_checks_part2() {
5562 let chanmon_cfgs = create_chanmon_cfgs(2);
5563 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5564 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5565 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5567 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5568 let channel_value_satoshis=2^24;
5569 let push_msat=10001;
5570 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5572 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5573 let channel_value_satoshis=10000;
5574 // Test when push_msat is equal to 1000 * funding_satoshis.
5575 let push_msat=1000*channel_value_satoshis+1;
5576 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5578 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5579 let channel_value_satoshis=10000;
5580 let push_msat=10001;
5581 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
5582 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5583 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5585 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5586 // 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
5587 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5589 // 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.
5590 assert!(BREAKDOWN_TIMEOUT>0);
5591 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5593 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5594 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5595 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5597 // 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.
5598 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5599 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5600 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5601 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5602 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5606 fn bolt2_open_channel_sane_dust_limit() {
5607 let chanmon_cfgs = create_chanmon_cfgs(2);
5608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5610 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5612 let channel_value_satoshis=1000000;
5613 let push_msat=10001;
5614 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5615 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5616 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5617 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5619 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5620 let events = nodes[1].node.get_and_clear_pending_msg_events();
5621 let err_msg = match events[0] {
5622 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5625 _ => panic!("Unexpected event"),
5627 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5630 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5631 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5632 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5633 // is no longer affordable once it's freed.
5635 fn test_fail_holding_cell_htlc_upon_free() {
5636 let chanmon_cfgs = create_chanmon_cfgs(2);
5637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5640 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5642 // First nodes[0] generates an update_fee, setting the channel's
5643 // pending_update_fee.
5645 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5646 *feerate_lock += 20;
5648 nodes[0].node.timer_tick_occurred();
5649 check_added_monitors!(nodes[0], 1);
5651 let events = nodes[0].node.get_and_clear_pending_msg_events();
5652 assert_eq!(events.len(), 1);
5653 let (update_msg, commitment_signed) = match events[0] {
5654 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5655 (update_fee.as_ref(), commitment_signed)
5657 _ => panic!("Unexpected event"),
5660 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5662 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5663 let channel_reserve = chan_stat.channel_reserve_msat;
5664 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5665 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5667 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5668 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5669 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5671 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5672 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5673 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5674 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5676 // Flush the pending fee update.
5677 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5678 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5679 check_added_monitors!(nodes[1], 1);
5680 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5681 check_added_monitors!(nodes[0], 1);
5683 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5684 // HTLC, but now that the fee has been raised the payment will now fail, causing
5685 // us to surface its failure to the user.
5686 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5687 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5688 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);
5689 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 {}",
5690 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5691 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5693 // Check that the payment failed to be sent out.
5694 let events = nodes[0].node.get_and_clear_pending_events();
5695 assert_eq!(events.len(), 2);
5697 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5698 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5699 assert_eq!(our_payment_hash.clone(), *payment_hash);
5700 assert_eq!(*payment_failed_permanently, false);
5701 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5703 _ => panic!("Unexpected event"),
5706 &Event::PaymentFailed { ref payment_hash, .. } => {
5707 assert_eq!(our_payment_hash.clone(), *payment_hash);
5709 _ => panic!("Unexpected event"),
5713 // Test that if multiple HTLCs are released from the holding cell and one is
5714 // valid but the other is no longer valid upon release, the valid HTLC can be
5715 // successfully completed while the other one fails as expected.
5717 fn test_free_and_fail_holding_cell_htlcs() {
5718 let chanmon_cfgs = create_chanmon_cfgs(2);
5719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5721 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5722 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5724 // First nodes[0] generates an update_fee, setting the channel's
5725 // pending_update_fee.
5727 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5728 *feerate_lock += 200;
5730 nodes[0].node.timer_tick_occurred();
5731 check_added_monitors!(nodes[0], 1);
5733 let events = nodes[0].node.get_and_clear_pending_msg_events();
5734 assert_eq!(events.len(), 1);
5735 let (update_msg, commitment_signed) = match events[0] {
5736 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5737 (update_fee.as_ref(), commitment_signed)
5739 _ => panic!("Unexpected event"),
5742 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5744 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5745 let channel_reserve = chan_stat.channel_reserve_msat;
5746 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5747 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5749 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5751 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5752 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5753 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5755 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5756 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5757 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5758 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5759 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5760 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2), payment_id_2).unwrap();
5761 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5762 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5764 // Flush the pending fee update.
5765 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5766 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5767 check_added_monitors!(nodes[1], 1);
5768 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5769 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5770 check_added_monitors!(nodes[0], 2);
5772 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5773 // but now that the fee has been raised the second payment will now fail, causing us
5774 // to surface its failure to the user. The first payment should succeed.
5775 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5776 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5777 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);
5778 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 {}",
5779 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5780 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5782 // Check that the second payment failed to be sent out.
5783 let events = nodes[0].node.get_and_clear_pending_events();
5784 assert_eq!(events.len(), 2);
5786 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5787 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5788 assert_eq!(payment_hash_2.clone(), *payment_hash);
5789 assert_eq!(*payment_failed_permanently, false);
5790 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5792 _ => panic!("Unexpected event"),
5795 &Event::PaymentFailed { ref payment_hash, .. } => {
5796 assert_eq!(payment_hash_2.clone(), *payment_hash);
5798 _ => panic!("Unexpected event"),
5801 // Complete the first payment and the RAA from the fee update.
5802 let (payment_event, send_raa_event) = {
5803 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5804 assert_eq!(msgs.len(), 2);
5805 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5807 let raa = match send_raa_event {
5808 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5809 _ => panic!("Unexpected event"),
5811 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5812 check_added_monitors!(nodes[1], 1);
5813 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5814 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5815 let events = nodes[1].node.get_and_clear_pending_events();
5816 assert_eq!(events.len(), 1);
5818 Event::PendingHTLCsForwardable { .. } => {},
5819 _ => panic!("Unexpected event"),
5821 nodes[1].node.process_pending_htlc_forwards();
5822 let events = nodes[1].node.get_and_clear_pending_events();
5823 assert_eq!(events.len(), 1);
5825 Event::PaymentClaimable { .. } => {},
5826 _ => panic!("Unexpected event"),
5828 nodes[1].node.claim_funds(payment_preimage_1);
5829 check_added_monitors!(nodes[1], 1);
5830 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5832 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5833 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5834 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5835 expect_payment_sent!(nodes[0], payment_preimage_1);
5838 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5839 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5840 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5843 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5844 let chanmon_cfgs = create_chanmon_cfgs(3);
5845 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5846 // When this test was written, the default base fee floated based on the HTLC count.
5847 // It is now fixed, so we simply set the fee to the expected value here.
5848 let mut config = test_default_channel_config();
5849 config.channel_config.forwarding_fee_base_msat = 196;
5850 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5851 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5852 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5853 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5855 // First nodes[1] generates an update_fee, setting the channel's
5856 // pending_update_fee.
5858 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5859 *feerate_lock += 20;
5861 nodes[1].node.timer_tick_occurred();
5862 check_added_monitors!(nodes[1], 1);
5864 let events = nodes[1].node.get_and_clear_pending_msg_events();
5865 assert_eq!(events.len(), 1);
5866 let (update_msg, commitment_signed) = match events[0] {
5867 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5868 (update_fee.as_ref(), commitment_signed)
5870 _ => panic!("Unexpected event"),
5873 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5875 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5876 let channel_reserve = chan_stat.channel_reserve_msat;
5877 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5878 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5880 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5882 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5883 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5884 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5885 let payment_event = {
5886 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5887 check_added_monitors!(nodes[0], 1);
5889 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5890 assert_eq!(events.len(), 1);
5892 SendEvent::from_event(events.remove(0))
5894 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5895 check_added_monitors!(nodes[1], 0);
5896 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5897 expect_pending_htlcs_forwardable!(nodes[1]);
5899 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5900 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5902 // Flush the pending fee update.
5903 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5904 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5905 check_added_monitors!(nodes[2], 1);
5906 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5907 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5908 check_added_monitors!(nodes[1], 2);
5910 // A final RAA message is generated to finalize the fee update.
5911 let events = nodes[1].node.get_and_clear_pending_msg_events();
5912 assert_eq!(events.len(), 1);
5914 let raa_msg = match &events[0] {
5915 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5918 _ => panic!("Unexpected event"),
5921 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5922 check_added_monitors!(nodes[2], 1);
5923 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5925 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5926 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5927 assert_eq!(process_htlc_forwards_event.len(), 2);
5928 match &process_htlc_forwards_event[0] {
5929 &Event::PendingHTLCsForwardable { .. } => {},
5930 _ => panic!("Unexpected event"),
5933 // In response, we call ChannelManager's process_pending_htlc_forwards
5934 nodes[1].node.process_pending_htlc_forwards();
5935 check_added_monitors!(nodes[1], 1);
5937 // This causes the HTLC to be failed backwards.
5938 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5939 assert_eq!(fail_event.len(), 1);
5940 let (fail_msg, commitment_signed) = match &fail_event[0] {
5941 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5942 assert_eq!(updates.update_add_htlcs.len(), 0);
5943 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5944 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5945 assert_eq!(updates.update_fail_htlcs.len(), 1);
5946 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5948 _ => panic!("Unexpected event"),
5951 // Pass the failure messages back to nodes[0].
5952 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5953 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5955 // Complete the HTLC failure+removal process.
5956 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5957 check_added_monitors!(nodes[0], 1);
5958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5959 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5960 check_added_monitors!(nodes[1], 2);
5961 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5962 assert_eq!(final_raa_event.len(), 1);
5963 let raa = match &final_raa_event[0] {
5964 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5965 _ => panic!("Unexpected event"),
5967 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5968 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5969 check_added_monitors!(nodes[0], 1);
5972 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5973 // 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.
5974 //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.
5977 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5978 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5979 let chanmon_cfgs = create_chanmon_cfgs(2);
5980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5983 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5985 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
5986 route.paths[0][0].fee_msat = 100;
5988 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 },
5989 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
5990 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5991 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
5995 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5996 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5997 let chanmon_cfgs = create_chanmon_cfgs(2);
5998 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5999 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6000 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6001 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6003 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6004 route.paths[0][0].fee_msat = 0;
6005 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 },
6006 assert_eq!(err, "Cannot send 0-msat HTLC"));
6008 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6009 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6013 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6014 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6015 let chanmon_cfgs = create_chanmon_cfgs(2);
6016 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6017 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6018 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6019 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6021 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6022 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6023 check_added_monitors!(nodes[0], 1);
6024 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6025 updates.update_add_htlcs[0].amount_msat = 0;
6027 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6028 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6029 check_closed_broadcast!(nodes[1], true).unwrap();
6030 check_added_monitors!(nodes[1], 1);
6031 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6035 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6036 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6037 //It is enforced when constructing a route.
6038 let chanmon_cfgs = create_chanmon_cfgs(2);
6039 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6040 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6041 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6042 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6044 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6045 .with_features(nodes[1].node.invoice_features());
6046 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6047 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6048 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 },
6049 assert_eq!(err, &"Channel CLTV overflowed?"));
6053 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6054 //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.
6055 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6056 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6057 let chanmon_cfgs = create_chanmon_cfgs(2);
6058 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6059 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6060 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6061 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6062 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6063 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6065 for i in 0..max_accepted_htlcs {
6066 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6067 let payment_event = {
6068 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6069 check_added_monitors!(nodes[0], 1);
6071 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6072 assert_eq!(events.len(), 1);
6073 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6074 assert_eq!(htlcs[0].htlc_id, i);
6078 SendEvent::from_event(events.remove(0))
6080 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6081 check_added_monitors!(nodes[1], 0);
6082 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6084 expect_pending_htlcs_forwardable!(nodes[1]);
6085 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6087 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6088 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 },
6089 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6091 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6092 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6096 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6097 //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.
6098 let chanmon_cfgs = create_chanmon_cfgs(2);
6099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6101 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6102 let channel_value = 100000;
6103 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6104 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6106 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6108 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6109 // Manually create a route over our max in flight (which our router normally automatically
6111 route.paths[0][0].fee_msat = max_in_flight + 1;
6112 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 },
6113 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)));
6115 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6116 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);
6118 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6121 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6123 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6124 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6125 let chanmon_cfgs = create_chanmon_cfgs(2);
6126 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6128 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6129 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6130 let htlc_minimum_msat: u64;
6132 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6133 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6134 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6135 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6138 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6139 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6140 check_added_monitors!(nodes[0], 1);
6141 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6142 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6143 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6144 assert!(nodes[1].node.list_channels().is_empty());
6145 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6146 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()));
6147 check_added_monitors!(nodes[1], 1);
6148 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6152 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6153 //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
6154 let chanmon_cfgs = create_chanmon_cfgs(2);
6155 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6156 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6157 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6158 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6160 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6161 let channel_reserve = chan_stat.channel_reserve_msat;
6162 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6163 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6164 // The 2* and +1 are for the fee spike reserve.
6165 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6167 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6168 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6169 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6170 check_added_monitors!(nodes[0], 1);
6171 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6173 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6174 // at this time channel-initiatee receivers are not required to enforce that senders
6175 // respect the fee_spike_reserve.
6176 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6177 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6179 assert!(nodes[1].node.list_channels().is_empty());
6180 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6181 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6182 check_added_monitors!(nodes[1], 1);
6183 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6187 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6188 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6189 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6190 let chanmon_cfgs = create_chanmon_cfgs(2);
6191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6193 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6194 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6196 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6197 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6198 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6199 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6200 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6201 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6203 let mut msg = msgs::UpdateAddHTLC {
6207 payment_hash: our_payment_hash,
6208 cltv_expiry: htlc_cltv,
6209 onion_routing_packet: onion_packet.clone(),
6212 for i in 0..super::channel::OUR_MAX_HTLCS {
6213 msg.htlc_id = i as u64;
6214 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6216 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6219 assert!(nodes[1].node.list_channels().is_empty());
6220 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6221 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6222 check_added_monitors!(nodes[1], 1);
6223 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6227 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6228 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6229 let chanmon_cfgs = create_chanmon_cfgs(2);
6230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6232 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6233 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6235 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6236 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6237 check_added_monitors!(nodes[0], 1);
6238 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6239 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;
6240 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6242 assert!(nodes[1].node.list_channels().is_empty());
6243 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6244 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6245 check_added_monitors!(nodes[1], 1);
6246 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6250 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6251 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6252 let chanmon_cfgs = create_chanmon_cfgs(2);
6253 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6254 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6255 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6257 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6259 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6260 check_added_monitors!(nodes[0], 1);
6261 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6262 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6263 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6265 assert!(nodes[1].node.list_channels().is_empty());
6266 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6267 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6268 check_added_monitors!(nodes[1], 1);
6269 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6273 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6274 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6275 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6276 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6277 let chanmon_cfgs = create_chanmon_cfgs(2);
6278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6280 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6282 create_announced_chan_between_nodes(&nodes, 0, 1);
6283 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6284 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6285 check_added_monitors!(nodes[0], 1);
6286 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6287 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6289 //Disconnect and Reconnect
6290 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6291 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6292 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();
6293 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6294 assert_eq!(reestablish_1.len(), 1);
6295 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();
6296 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6297 assert_eq!(reestablish_2.len(), 1);
6298 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6299 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6300 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6301 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6305 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6306 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6307 check_added_monitors!(nodes[1], 1);
6308 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6310 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6312 assert!(nodes[1].node.list_channels().is_empty());
6313 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6314 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6315 check_added_monitors!(nodes[1], 1);
6316 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6320 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6321 //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.
6323 let chanmon_cfgs = create_chanmon_cfgs(2);
6324 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6325 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6326 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6327 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6328 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6329 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6331 check_added_monitors!(nodes[0], 1);
6332 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6335 let update_msg = msgs::UpdateFulfillHTLC{
6338 payment_preimage: our_payment_preimage,
6341 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6343 assert!(nodes[0].node.list_channels().is_empty());
6344 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6345 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()));
6346 check_added_monitors!(nodes[0], 1);
6347 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6351 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6352 //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.
6354 let chanmon_cfgs = create_chanmon_cfgs(2);
6355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6357 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6358 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6360 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6361 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6362 check_added_monitors!(nodes[0], 1);
6363 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6364 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6366 let update_msg = msgs::UpdateFailHTLC{
6369 reason: msgs::OnionErrorPacket { data: Vec::new()},
6372 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6374 assert!(nodes[0].node.list_channels().is_empty());
6375 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6376 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()));
6377 check_added_monitors!(nodes[0], 1);
6378 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6382 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6383 //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.
6385 let chanmon_cfgs = create_chanmon_cfgs(2);
6386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6389 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6391 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6392 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6393 check_added_monitors!(nodes[0], 1);
6394 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6395 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6396 let update_msg = msgs::UpdateFailMalformedHTLC{
6399 sha256_of_onion: [1; 32],
6400 failure_code: 0x8000,
6403 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6405 assert!(nodes[0].node.list_channels().is_empty());
6406 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6407 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()));
6408 check_added_monitors!(nodes[0], 1);
6409 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6413 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6414 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6416 let chanmon_cfgs = create_chanmon_cfgs(2);
6417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6419 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6420 create_announced_chan_between_nodes(&nodes, 0, 1);
6422 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6424 nodes[1].node.claim_funds(our_payment_preimage);
6425 check_added_monitors!(nodes[1], 1);
6426 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6428 let events = nodes[1].node.get_and_clear_pending_msg_events();
6429 assert_eq!(events.len(), 1);
6430 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6432 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, .. } } => {
6433 assert!(update_add_htlcs.is_empty());
6434 assert_eq!(update_fulfill_htlcs.len(), 1);
6435 assert!(update_fail_htlcs.is_empty());
6436 assert!(update_fail_malformed_htlcs.is_empty());
6437 assert!(update_fee.is_none());
6438 update_fulfill_htlcs[0].clone()
6440 _ => panic!("Unexpected event"),
6444 update_fulfill_msg.htlc_id = 1;
6446 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6448 assert!(nodes[0].node.list_channels().is_empty());
6449 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6450 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6451 check_added_monitors!(nodes[0], 1);
6452 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6456 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6457 //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.
6459 let chanmon_cfgs = create_chanmon_cfgs(2);
6460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463 create_announced_chan_between_nodes(&nodes, 0, 1);
6465 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6467 nodes[1].node.claim_funds(our_payment_preimage);
6468 check_added_monitors!(nodes[1], 1);
6469 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6471 let events = nodes[1].node.get_and_clear_pending_msg_events();
6472 assert_eq!(events.len(), 1);
6473 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6475 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, .. } } => {
6476 assert!(update_add_htlcs.is_empty());
6477 assert_eq!(update_fulfill_htlcs.len(), 1);
6478 assert!(update_fail_htlcs.is_empty());
6479 assert!(update_fail_malformed_htlcs.is_empty());
6480 assert!(update_fee.is_none());
6481 update_fulfill_htlcs[0].clone()
6483 _ => panic!("Unexpected event"),
6487 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6489 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6491 assert!(nodes[0].node.list_channels().is_empty());
6492 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6493 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6494 check_added_monitors!(nodes[0], 1);
6495 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6499 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6500 //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.
6502 let chanmon_cfgs = create_chanmon_cfgs(2);
6503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6506 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6508 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6509 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6510 check_added_monitors!(nodes[0], 1);
6512 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6513 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6515 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6516 check_added_monitors!(nodes[1], 0);
6517 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6519 let events = nodes[1].node.get_and_clear_pending_msg_events();
6521 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6523 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, .. } } => {
6524 assert!(update_add_htlcs.is_empty());
6525 assert!(update_fulfill_htlcs.is_empty());
6526 assert!(update_fail_htlcs.is_empty());
6527 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6528 assert!(update_fee.is_none());
6529 update_fail_malformed_htlcs[0].clone()
6531 _ => panic!("Unexpected event"),
6534 update_msg.failure_code &= !0x8000;
6535 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6537 assert!(nodes[0].node.list_channels().is_empty());
6538 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6539 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6540 check_added_monitors!(nodes[0], 1);
6541 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6545 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6546 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6547 // * 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.
6549 let chanmon_cfgs = create_chanmon_cfgs(3);
6550 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6551 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6552 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6553 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6554 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6556 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6559 let mut payment_event = {
6560 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6561 check_added_monitors!(nodes[0], 1);
6562 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6563 assert_eq!(events.len(), 1);
6564 SendEvent::from_event(events.remove(0))
6566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6567 check_added_monitors!(nodes[1], 0);
6568 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6569 expect_pending_htlcs_forwardable!(nodes[1]);
6570 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6571 assert_eq!(events_2.len(), 1);
6572 check_added_monitors!(nodes[1], 1);
6573 payment_event = SendEvent::from_event(events_2.remove(0));
6574 assert_eq!(payment_event.msgs.len(), 1);
6577 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6578 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6579 check_added_monitors!(nodes[2], 0);
6580 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6582 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6583 assert_eq!(events_3.len(), 1);
6584 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6586 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 } } => {
6587 assert!(update_add_htlcs.is_empty());
6588 assert!(update_fulfill_htlcs.is_empty());
6589 assert!(update_fail_htlcs.is_empty());
6590 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6591 assert!(update_fee.is_none());
6592 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6594 _ => panic!("Unexpected event"),
6598 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6600 check_added_monitors!(nodes[1], 0);
6601 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6602 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 }]);
6603 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6604 assert_eq!(events_4.len(), 1);
6606 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6608 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, .. } } => {
6609 assert!(update_add_htlcs.is_empty());
6610 assert!(update_fulfill_htlcs.is_empty());
6611 assert_eq!(update_fail_htlcs.len(), 1);
6612 assert!(update_fail_malformed_htlcs.is_empty());
6613 assert!(update_fee.is_none());
6615 _ => panic!("Unexpected event"),
6618 check_added_monitors!(nodes[1], 1);
6622 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6623 let chanmon_cfgs = create_chanmon_cfgs(3);
6624 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6625 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6626 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6627 create_announced_chan_between_nodes(&nodes, 0, 1);
6628 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6630 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6633 let mut payment_event = {
6634 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6635 check_added_monitors!(nodes[0], 1);
6636 SendEvent::from_node(&nodes[0])
6639 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6640 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6641 expect_pending_htlcs_forwardable!(nodes[1]);
6642 check_added_monitors!(nodes[1], 1);
6643 payment_event = SendEvent::from_node(&nodes[1]);
6644 assert_eq!(payment_event.msgs.len(), 1);
6647 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6648 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6649 check_added_monitors!(nodes[2], 0);
6650 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6652 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6653 assert_eq!(events_3.len(), 1);
6655 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6656 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6657 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6658 update_msg.failure_code |= 0x2000;
6660 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6661 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6663 _ => panic!("Unexpected event"),
6666 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6667 vec![HTLCDestination::NextHopChannel {
6668 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6669 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6670 assert_eq!(events_4.len(), 1);
6671 check_added_monitors!(nodes[1], 1);
6674 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6675 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6676 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6678 _ => panic!("Unexpected event"),
6681 let events_5 = nodes[0].node.get_and_clear_pending_events();
6682 assert_eq!(events_5.len(), 2);
6684 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6685 // the node originating the error to its next hop.
6687 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6689 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6690 assert!(is_permanent);
6691 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6693 _ => panic!("Unexpected event"),
6696 Event::PaymentFailed { payment_hash, .. } => {
6697 assert_eq!(payment_hash, our_payment_hash);
6699 _ => panic!("Unexpected event"),
6702 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6705 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6706 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6707 // 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
6708 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6710 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6711 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6714 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6715 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6717 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6718 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6720 // We route 2 dust-HTLCs between A and B
6721 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6722 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6723 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6725 // Cache one local commitment tx as previous
6726 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6728 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6729 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6730 check_added_monitors!(nodes[1], 0);
6731 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6732 check_added_monitors!(nodes[1], 1);
6734 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6735 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6736 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6737 check_added_monitors!(nodes[0], 1);
6739 // Cache one local commitment tx as lastest
6740 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6742 let events = nodes[0].node.get_and_clear_pending_msg_events();
6744 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6745 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6747 _ => panic!("Unexpected event"),
6750 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6751 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6753 _ => panic!("Unexpected event"),
6756 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6757 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6758 if announce_latest {
6759 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6761 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6764 check_closed_broadcast!(nodes[0], true);
6765 check_added_monitors!(nodes[0], 1);
6766 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6768 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6769 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6770 let events = nodes[0].node.get_and_clear_pending_events();
6771 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6772 assert_eq!(events.len(), 4);
6773 let mut first_failed = false;
6774 for event in events {
6776 Event::PaymentPathFailed { payment_hash, .. } => {
6777 if payment_hash == payment_hash_1 {
6778 assert!(!first_failed);
6779 first_failed = true;
6781 assert_eq!(payment_hash, payment_hash_2);
6784 Event::PaymentFailed { .. } => {}
6785 _ => panic!("Unexpected event"),
6791 fn test_failure_delay_dust_htlc_local_commitment() {
6792 do_test_failure_delay_dust_htlc_local_commitment(true);
6793 do_test_failure_delay_dust_htlc_local_commitment(false);
6796 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6797 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6798 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6799 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6800 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6801 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6802 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6804 let chanmon_cfgs = create_chanmon_cfgs(3);
6805 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6806 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6807 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6808 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6810 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6811 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6813 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6814 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6816 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6817 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6819 // We revoked bs_commitment_tx
6821 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6822 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6825 let mut timeout_tx = Vec::new();
6827 // We fail dust-HTLC 1 by broadcast of local commitment tx
6828 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6829 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6830 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6831 expect_payment_failed!(nodes[0], dust_hash, false);
6833 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6834 check_closed_broadcast!(nodes[0], true);
6835 check_added_monitors!(nodes[0], 1);
6836 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6837 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6838 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6839 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6840 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6841 mine_transaction(&nodes[0], &timeout_tx[0]);
6842 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6843 expect_payment_failed!(nodes[0], non_dust_hash, false);
6845 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6846 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6847 check_closed_broadcast!(nodes[0], true);
6848 check_added_monitors!(nodes[0], 1);
6849 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6850 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6852 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6853 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6854 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6855 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6856 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6857 // dust HTLC should have been failed.
6858 expect_payment_failed!(nodes[0], dust_hash, false);
6861 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6863 assert_eq!(timeout_tx[0].lock_time.0, 12);
6865 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6866 mine_transaction(&nodes[0], &timeout_tx[0]);
6867 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6868 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6869 expect_payment_failed!(nodes[0], non_dust_hash, false);
6874 fn test_sweep_outbound_htlc_failure_update() {
6875 do_test_sweep_outbound_htlc_failure_update(false, true);
6876 do_test_sweep_outbound_htlc_failure_update(false, false);
6877 do_test_sweep_outbound_htlc_failure_update(true, false);
6881 fn test_user_configurable_csv_delay() {
6882 // We test our channel constructors yield errors when we pass them absurd csv delay
6884 let mut low_our_to_self_config = UserConfig::default();
6885 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6886 let mut high_their_to_self_config = UserConfig::default();
6887 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6888 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6889 let chanmon_cfgs = create_chanmon_cfgs(2);
6890 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6891 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6892 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6894 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6895 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6896 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6897 &low_our_to_self_config, 0, 42)
6900 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())); },
6901 _ => panic!("Unexpected event"),
6903 } else { assert!(false) }
6905 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6906 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6907 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6908 open_channel.to_self_delay = 200;
6909 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6910 &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,
6911 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6914 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())); },
6915 _ => panic!("Unexpected event"),
6917 } else { assert!(false); }
6919 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6920 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6921 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()));
6922 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6923 accept_channel.to_self_delay = 200;
6924 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6926 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6928 &ErrorAction::SendErrorMessage { ref msg } => {
6929 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()));
6930 reason_msg = msg.data.clone();
6934 } else { panic!(); }
6935 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6937 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6938 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6939 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6940 open_channel.to_self_delay = 200;
6941 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6942 &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,
6943 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6946 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())); },
6947 _ => panic!("Unexpected event"),
6949 } else { assert!(false); }
6953 fn test_check_htlc_underpaying() {
6954 // Send payment through A -> B but A is maliciously
6955 // sending a probe payment (i.e less than expected value0
6956 // to B, B should refuse payment.
6958 let chanmon_cfgs = create_chanmon_cfgs(2);
6959 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6960 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6961 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6963 // Create some initial channels
6964 create_announced_chan_between_nodes(&nodes, 0, 1);
6966 let scorer = test_utils::TestScorer::new();
6967 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
6968 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
6969 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();
6970 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
6971 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
6972 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6973 check_added_monitors!(nodes[0], 1);
6975 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6976 assert_eq!(events.len(), 1);
6977 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
6978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6979 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6981 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
6982 // and then will wait a second random delay before failing the HTLC back:
6983 expect_pending_htlcs_forwardable!(nodes[1]);
6984 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
6986 // Node 3 is expecting payment of 100_000 but received 10_000,
6987 // it should fail htlc like we didn't know the preimage.
6988 nodes[1].node.process_pending_htlc_forwards();
6990 let events = nodes[1].node.get_and_clear_pending_msg_events();
6991 assert_eq!(events.len(), 1);
6992 let (update_fail_htlc, commitment_signed) = match events[0] {
6993 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 } } => {
6994 assert!(update_add_htlcs.is_empty());
6995 assert!(update_fulfill_htlcs.is_empty());
6996 assert_eq!(update_fail_htlcs.len(), 1);
6997 assert!(update_fail_malformed_htlcs.is_empty());
6998 assert!(update_fee.is_none());
6999 (update_fail_htlcs[0].clone(), commitment_signed)
7001 _ => panic!("Unexpected event"),
7003 check_added_monitors!(nodes[1], 1);
7005 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7006 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7008 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7009 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7010 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7011 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7015 fn test_announce_disable_channels() {
7016 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7017 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7019 let chanmon_cfgs = create_chanmon_cfgs(2);
7020 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7021 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7022 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7024 create_announced_chan_between_nodes(&nodes, 0, 1);
7025 create_announced_chan_between_nodes(&nodes, 1, 0);
7026 create_announced_chan_between_nodes(&nodes, 0, 1);
7029 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7030 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7032 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7033 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7034 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7035 assert_eq!(msg_events.len(), 3);
7036 let mut chans_disabled = HashMap::new();
7037 for e in msg_events {
7039 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7040 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7041 // Check that each channel gets updated exactly once
7042 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7043 panic!("Generated ChannelUpdate for wrong chan!");
7046 _ => panic!("Unexpected event"),
7050 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();
7051 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7052 assert_eq!(reestablish_1.len(), 3);
7053 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();
7054 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7055 assert_eq!(reestablish_2.len(), 3);
7057 // Reestablish chan_1
7058 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7059 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7060 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7061 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7062 // Reestablish chan_2
7063 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7064 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7065 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7066 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7067 // Reestablish chan_3
7068 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7069 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7070 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7071 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7073 nodes[0].node.timer_tick_occurred();
7074 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7075 nodes[0].node.timer_tick_occurred();
7076 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7077 assert_eq!(msg_events.len(), 3);
7078 for e in msg_events {
7080 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7081 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7082 match chans_disabled.remove(&msg.contents.short_channel_id) {
7083 // Each update should have a higher timestamp than the previous one, replacing
7085 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7086 None => panic!("Generated ChannelUpdate for wrong chan!"),
7089 _ => panic!("Unexpected event"),
7092 // Check that each channel gets updated exactly once
7093 assert!(chans_disabled.is_empty());
7097 fn test_bump_penalty_txn_on_revoked_commitment() {
7098 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7099 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7101 let chanmon_cfgs = create_chanmon_cfgs(2);
7102 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7103 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7104 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7106 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7108 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7109 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7110 .with_features(nodes[0].node.invoice_features());
7111 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7112 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7114 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7115 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7116 assert_eq!(revoked_txn[0].output.len(), 4);
7117 assert_eq!(revoked_txn[0].input.len(), 1);
7118 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7119 let revoked_txid = revoked_txn[0].txid();
7121 let mut penalty_sum = 0;
7122 for outp in revoked_txn[0].output.iter() {
7123 if outp.script_pubkey.is_v0_p2wsh() {
7124 penalty_sum += outp.value;
7128 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7129 let header_114 = connect_blocks(&nodes[1], 14);
7131 // Actually revoke tx by claiming a HTLC
7132 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7133 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7134 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7135 check_added_monitors!(nodes[1], 1);
7137 // One or more justice tx should have been broadcast, check it
7141 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7142 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7143 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7144 assert_eq!(node_txn[0].output.len(), 1);
7145 check_spends!(node_txn[0], revoked_txn[0]);
7146 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7147 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7148 penalty_1 = node_txn[0].txid();
7152 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7153 connect_blocks(&nodes[1], 15);
7154 let mut penalty_2 = penalty_1;
7155 let mut feerate_2 = 0;
7157 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7158 assert_eq!(node_txn.len(), 1);
7159 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7160 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7161 assert_eq!(node_txn[0].output.len(), 1);
7162 check_spends!(node_txn[0], revoked_txn[0]);
7163 penalty_2 = node_txn[0].txid();
7164 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7165 assert_ne!(penalty_2, penalty_1);
7166 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7167 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7168 // Verify 25% bump heuristic
7169 assert!(feerate_2 * 100 >= feerate_1 * 125);
7173 assert_ne!(feerate_2, 0);
7175 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7176 connect_blocks(&nodes[1], 1);
7178 let mut feerate_3 = 0;
7180 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7181 assert_eq!(node_txn.len(), 1);
7182 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7183 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7184 assert_eq!(node_txn[0].output.len(), 1);
7185 check_spends!(node_txn[0], revoked_txn[0]);
7186 penalty_3 = node_txn[0].txid();
7187 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7188 assert_ne!(penalty_3, penalty_2);
7189 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7190 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7191 // Verify 25% bump heuristic
7192 assert!(feerate_3 * 100 >= feerate_2 * 125);
7196 assert_ne!(feerate_3, 0);
7198 nodes[1].node.get_and_clear_pending_events();
7199 nodes[1].node.get_and_clear_pending_msg_events();
7203 fn test_bump_penalty_txn_on_revoked_htlcs() {
7204 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7205 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7207 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7208 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7209 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7210 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7211 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7213 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7214 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7215 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7216 let scorer = test_utils::TestScorer::new();
7217 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7218 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7219 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7220 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7221 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7222 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7223 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7224 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7226 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7227 assert_eq!(revoked_local_txn[0].input.len(), 1);
7228 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7230 // Revoke local commitment tx
7231 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7233 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7234 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7235 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7236 check_closed_broadcast!(nodes[1], true);
7237 check_added_monitors!(nodes[1], 1);
7238 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7239 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7241 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7242 assert_eq!(revoked_htlc_txn.len(), 2);
7244 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7245 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7246 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7248 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7249 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7250 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7251 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7253 // Broadcast set of revoked txn on A
7254 let hash_128 = connect_blocks(&nodes[0], 40);
7255 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7256 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7257 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7258 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7259 let events = nodes[0].node.get_and_clear_pending_events();
7260 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7261 match events.last().unwrap() {
7262 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7263 _ => panic!("Unexpected event"),
7269 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7270 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7271 // Verify claim tx are spending revoked HTLC txn
7273 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7274 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7275 // which are included in the same block (they are broadcasted because we scan the
7276 // transactions linearly and generate claims as we go, they likely should be removed in the
7278 assert_eq!(node_txn[0].input.len(), 1);
7279 check_spends!(node_txn[0], revoked_local_txn[0]);
7280 assert_eq!(node_txn[1].input.len(), 1);
7281 check_spends!(node_txn[1], revoked_local_txn[0]);
7282 assert_eq!(node_txn[2].input.len(), 1);
7283 check_spends!(node_txn[2], revoked_local_txn[0]);
7285 // Each of the three justice transactions claim a separate (single) output of the three
7286 // available, which we check here:
7287 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7288 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7289 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7291 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7292 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7294 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7295 // output, checked above).
7296 assert_eq!(node_txn[3].input.len(), 2);
7297 assert_eq!(node_txn[3].output.len(), 1);
7298 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7300 first = node_txn[3].txid();
7301 // Store both feerates for later comparison
7302 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7303 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7304 penalty_txn = vec![node_txn[2].clone()];
7308 // Connect one more block to see if bumped penalty are issued for HTLC txn
7309 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7310 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7311 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7312 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7314 // Few more blocks to confirm penalty txn
7315 connect_blocks(&nodes[0], 4);
7316 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7317 let header_144 = connect_blocks(&nodes[0], 9);
7319 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7320 assert_eq!(node_txn.len(), 1);
7322 assert_eq!(node_txn[0].input.len(), 2);
7323 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7324 // Verify bumped tx is different and 25% bump heuristic
7325 assert_ne!(first, node_txn[0].txid());
7326 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7327 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7328 assert!(feerate_2 * 100 > feerate_1 * 125);
7329 let txn = vec![node_txn[0].clone()];
7333 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7334 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7335 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7336 connect_blocks(&nodes[0], 20);
7338 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7339 // We verify than no new transaction has been broadcast because previously
7340 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7341 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7342 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7343 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7344 // up bumped justice generation.
7345 assert_eq!(node_txn.len(), 0);
7348 check_closed_broadcast!(nodes[0], true);
7349 check_added_monitors!(nodes[0], 1);
7353 fn test_bump_penalty_txn_on_remote_commitment() {
7354 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7355 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7358 // Provide preimage for one
7359 // Check aggregation
7361 let chanmon_cfgs = create_chanmon_cfgs(2);
7362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7364 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7366 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7367 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7368 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7370 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7371 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7372 assert_eq!(remote_txn[0].output.len(), 4);
7373 assert_eq!(remote_txn[0].input.len(), 1);
7374 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7376 // Claim a HTLC without revocation (provide B monitor with preimage)
7377 nodes[1].node.claim_funds(payment_preimage);
7378 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7379 mine_transaction(&nodes[1], &remote_txn[0]);
7380 check_added_monitors!(nodes[1], 2);
7381 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7383 // One or more claim tx should have been broadcast, check it
7387 let feerate_timeout;
7388 let feerate_preimage;
7390 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7391 // 3 transactions including:
7392 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7393 assert_eq!(node_txn.len(), 3);
7394 assert_eq!(node_txn[0].input.len(), 1);
7395 assert_eq!(node_txn[1].input.len(), 1);
7396 assert_eq!(node_txn[2].input.len(), 1);
7397 check_spends!(node_txn[0], remote_txn[0]);
7398 check_spends!(node_txn[1], remote_txn[0]);
7399 check_spends!(node_txn[2], remote_txn[0]);
7401 preimage = node_txn[0].txid();
7402 let index = node_txn[0].input[0].previous_output.vout;
7403 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7404 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7406 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7407 (node_txn[2].clone(), node_txn[1].clone())
7409 (node_txn[1].clone(), node_txn[2].clone())
7412 preimage_bump = preimage_bump_tx;
7413 check_spends!(preimage_bump, remote_txn[0]);
7414 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7416 timeout = timeout_tx.txid();
7417 let index = timeout_tx.input[0].previous_output.vout;
7418 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7419 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7423 assert_ne!(feerate_timeout, 0);
7424 assert_ne!(feerate_preimage, 0);
7426 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7427 connect_blocks(&nodes[1], 15);
7429 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7430 assert_eq!(node_txn.len(), 1);
7431 assert_eq!(node_txn[0].input.len(), 1);
7432 assert_eq!(preimage_bump.input.len(), 1);
7433 check_spends!(node_txn[0], remote_txn[0]);
7434 check_spends!(preimage_bump, remote_txn[0]);
7436 let index = preimage_bump.input[0].previous_output.vout;
7437 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7438 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7439 assert!(new_feerate * 100 > feerate_timeout * 125);
7440 assert_ne!(timeout, preimage_bump.txid());
7442 let index = node_txn[0].input[0].previous_output.vout;
7443 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7444 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7445 assert!(new_feerate * 100 > feerate_preimage * 125);
7446 assert_ne!(preimage, node_txn[0].txid());
7451 nodes[1].node.get_and_clear_pending_events();
7452 nodes[1].node.get_and_clear_pending_msg_events();
7456 fn test_counterparty_raa_skip_no_crash() {
7457 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7458 // commitment transaction, we would have happily carried on and provided them the next
7459 // commitment transaction based on one RAA forward. This would probably eventually have led to
7460 // channel closure, but it would not have resulted in funds loss. Still, our
7461 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7462 // check simply that the channel is closed in response to such an RAA, but don't check whether
7463 // we decide to punish our counterparty for revoking their funds (as we don't currently
7465 let chanmon_cfgs = create_chanmon_cfgs(2);
7466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7468 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7469 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7471 let per_commitment_secret;
7472 let next_per_commitment_point;
7474 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7475 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7476 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7478 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7480 // Make signer believe we got a counterparty signature, so that it allows the revocation
7481 keys.get_enforcement_state().last_holder_commitment -= 1;
7482 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7484 // Must revoke without gaps
7485 keys.get_enforcement_state().last_holder_commitment -= 1;
7486 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7488 keys.get_enforcement_state().last_holder_commitment -= 1;
7489 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7490 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7493 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7494 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7495 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7496 check_added_monitors!(nodes[1], 1);
7497 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7501 fn test_bump_txn_sanitize_tracking_maps() {
7502 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7503 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7505 let chanmon_cfgs = create_chanmon_cfgs(2);
7506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7510 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7511 // Lock HTLC in both directions
7512 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7513 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7515 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7516 assert_eq!(revoked_local_txn[0].input.len(), 1);
7517 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7519 // Revoke local commitment tx
7520 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7522 // Broadcast set of revoked txn on A
7523 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7524 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7525 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7527 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7528 check_closed_broadcast!(nodes[0], true);
7529 check_added_monitors!(nodes[0], 1);
7530 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7532 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7533 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7534 check_spends!(node_txn[0], revoked_local_txn[0]);
7535 check_spends!(node_txn[1], revoked_local_txn[0]);
7536 check_spends!(node_txn[2], revoked_local_txn[0]);
7537 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7541 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7542 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7543 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7545 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7546 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7547 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7552 fn test_pending_claimed_htlc_no_balance_underflow() {
7553 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7554 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7555 let chanmon_cfgs = create_chanmon_cfgs(2);
7556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7558 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7559 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7561 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7562 nodes[1].node.claim_funds(payment_preimage);
7563 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7564 check_added_monitors!(nodes[1], 1);
7565 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7567 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7568 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7569 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7570 check_added_monitors!(nodes[0], 1);
7571 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7573 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7574 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7575 // can get our balance.
7577 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7578 // the public key of the only hop. This works around ChannelDetails not showing the
7579 // almost-claimed HTLC as available balance.
7580 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7581 route.payment_params = None; // This is all wrong, but unnecessary
7582 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7583 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7584 nodes[1].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7586 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7590 fn test_channel_conf_timeout() {
7591 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7592 // confirm within 2016 blocks, as recommended by BOLT 2.
7593 let chanmon_cfgs = create_chanmon_cfgs(2);
7594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7598 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7600 // The outbound node should wait forever for confirmation:
7601 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7602 // copied here instead of directly referencing the constant.
7603 connect_blocks(&nodes[0], 2016);
7604 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7606 // The inbound node should fail the channel after exactly 2016 blocks
7607 connect_blocks(&nodes[1], 2015);
7608 check_added_monitors!(nodes[1], 0);
7609 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7611 connect_blocks(&nodes[1], 1);
7612 check_added_monitors!(nodes[1], 1);
7613 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7614 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7615 assert_eq!(close_ev.len(), 1);
7617 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7618 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7619 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7621 _ => panic!("Unexpected event"),
7626 fn test_override_channel_config() {
7627 let chanmon_cfgs = create_chanmon_cfgs(2);
7628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7630 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7632 // Node0 initiates a channel to node1 using the override config.
7633 let mut override_config = UserConfig::default();
7634 override_config.channel_handshake_config.our_to_self_delay = 200;
7636 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7638 // Assert the channel created by node0 is using the override config.
7639 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7640 assert_eq!(res.channel_flags, 0);
7641 assert_eq!(res.to_self_delay, 200);
7645 fn test_override_0msat_htlc_minimum() {
7646 let mut zero_config = UserConfig::default();
7647 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7648 let chanmon_cfgs = create_chanmon_cfgs(2);
7649 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7650 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7651 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7653 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7654 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7655 assert_eq!(res.htlc_minimum_msat, 1);
7657 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7658 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7659 assert_eq!(res.htlc_minimum_msat, 1);
7663 fn test_channel_update_has_correct_htlc_maximum_msat() {
7664 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7665 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7666 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7667 // 90% of the `channel_value`.
7668 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7670 let mut config_30_percent = UserConfig::default();
7671 config_30_percent.channel_handshake_config.announced_channel = true;
7672 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7673 let mut config_50_percent = UserConfig::default();
7674 config_50_percent.channel_handshake_config.announced_channel = true;
7675 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7676 let mut config_95_percent = UserConfig::default();
7677 config_95_percent.channel_handshake_config.announced_channel = true;
7678 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7679 let mut config_100_percent = UserConfig::default();
7680 config_100_percent.channel_handshake_config.announced_channel = true;
7681 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7683 let chanmon_cfgs = create_chanmon_cfgs(4);
7684 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7685 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)]);
7686 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7688 let channel_value_satoshis = 100000;
7689 let channel_value_msat = channel_value_satoshis * 1000;
7690 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7691 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7692 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7694 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7695 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7697 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7698 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7699 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7700 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7701 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7702 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7704 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7705 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7707 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7708 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7709 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7711 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7715 fn test_manually_accept_inbound_channel_request() {
7716 let mut manually_accept_conf = UserConfig::default();
7717 manually_accept_conf.manually_accept_inbound_channels = true;
7718 let chanmon_cfgs = create_chanmon_cfgs(2);
7719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7721 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7723 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7724 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7726 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7728 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7729 // accepting the inbound channel request.
7730 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7732 let events = nodes[1].node.get_and_clear_pending_events();
7734 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7735 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7737 _ => panic!("Unexpected event"),
7740 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7741 assert_eq!(accept_msg_ev.len(), 1);
7743 match accept_msg_ev[0] {
7744 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7745 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7747 _ => panic!("Unexpected event"),
7750 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7752 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7753 assert_eq!(close_msg_ev.len(), 1);
7755 let events = nodes[1].node.get_and_clear_pending_events();
7757 Event::ChannelClosed { user_channel_id, .. } => {
7758 assert_eq!(user_channel_id, 23);
7760 _ => panic!("Unexpected event"),
7765 fn test_manually_reject_inbound_channel_request() {
7766 let mut manually_accept_conf = UserConfig::default();
7767 manually_accept_conf.manually_accept_inbound_channels = true;
7768 let chanmon_cfgs = create_chanmon_cfgs(2);
7769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7771 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7773 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7774 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7776 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7778 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7779 // rejecting the inbound channel request.
7780 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7782 let events = nodes[1].node.get_and_clear_pending_events();
7784 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7785 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7787 _ => panic!("Unexpected event"),
7790 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7791 assert_eq!(close_msg_ev.len(), 1);
7793 match close_msg_ev[0] {
7794 MessageSendEvent::HandleError { ref node_id, .. } => {
7795 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7797 _ => panic!("Unexpected event"),
7799 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7803 fn test_reject_funding_before_inbound_channel_accepted() {
7804 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7805 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7806 // the node operator before the counterparty sends a `FundingCreated` message. If a
7807 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7808 // and the channel should be closed.
7809 let mut manually_accept_conf = UserConfig::default();
7810 manually_accept_conf.manually_accept_inbound_channels = true;
7811 let chanmon_cfgs = create_chanmon_cfgs(2);
7812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7814 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7816 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7817 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7818 let temp_channel_id = res.temporary_channel_id;
7820 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7822 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7823 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7825 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7826 nodes[1].node.get_and_clear_pending_events();
7828 // Get the `AcceptChannel` message of `nodes[1]` without calling
7829 // `ChannelManager::accept_inbound_channel`, which generates a
7830 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7831 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7832 // succeed when `nodes[0]` is passed to it.
7833 let accept_chan_msg = {
7834 let mut node_1_per_peer_lock;
7835 let mut node_1_peer_state_lock;
7836 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7837 channel.get_accept_channel_message()
7839 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7841 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7843 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7844 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7846 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7847 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7849 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7850 assert_eq!(close_msg_ev.len(), 1);
7852 let expected_err = "FundingCreated message received before the channel was accepted";
7853 match close_msg_ev[0] {
7854 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7855 assert_eq!(msg.channel_id, temp_channel_id);
7856 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7857 assert_eq!(msg.data, expected_err);
7859 _ => panic!("Unexpected event"),
7862 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7866 fn test_can_not_accept_inbound_channel_twice() {
7867 let mut manually_accept_conf = UserConfig::default();
7868 manually_accept_conf.manually_accept_inbound_channels = true;
7869 let chanmon_cfgs = create_chanmon_cfgs(2);
7870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7872 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7874 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7875 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7877 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7879 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7880 // accepting the inbound channel request.
7881 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7883 let events = nodes[1].node.get_and_clear_pending_events();
7885 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7886 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7887 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7889 Err(APIError::APIMisuseError { err }) => {
7890 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7892 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7893 Err(_) => panic!("Unexpected Error"),
7896 _ => panic!("Unexpected event"),
7899 // Ensure that the channel wasn't closed after attempting to accept it twice.
7900 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7901 assert_eq!(accept_msg_ev.len(), 1);
7903 match accept_msg_ev[0] {
7904 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7905 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7907 _ => panic!("Unexpected event"),
7912 fn test_can_not_accept_unknown_inbound_channel() {
7913 let chanmon_cfg = create_chanmon_cfgs(2);
7914 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7915 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7916 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7918 let unknown_channel_id = [0; 32];
7919 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7921 Err(APIError::ChannelUnavailable { err }) => {
7922 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()));
7924 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7925 Err(_) => panic!("Unexpected Error"),
7930 fn test_simple_mpp() {
7931 // Simple test of sending a multi-path payment.
7932 let chanmon_cfgs = create_chanmon_cfgs(4);
7933 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7934 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7935 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7937 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7938 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7939 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7940 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7942 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
7943 let path = route.paths[0].clone();
7944 route.paths.push(path);
7945 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7946 route.paths[0][0].short_channel_id = chan_1_id;
7947 route.paths[0][1].short_channel_id = chan_3_id;
7948 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7949 route.paths[1][0].short_channel_id = chan_2_id;
7950 route.paths[1][1].short_channel_id = chan_4_id;
7951 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
7952 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
7956 fn test_preimage_storage() {
7957 // Simple test of payment preimage storage allowing no client-side storage to claim payments
7958 let chanmon_cfgs = create_chanmon_cfgs(2);
7959 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7960 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7961 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7963 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7966 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
7967 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
7968 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
7969 check_added_monitors!(nodes[0], 1);
7970 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7971 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7972 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7973 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7975 // Note that after leaving the above scope we have no knowledge of any arguments or return
7976 // values from previous calls.
7977 expect_pending_htlcs_forwardable!(nodes[1]);
7978 let events = nodes[1].node.get_and_clear_pending_events();
7979 assert_eq!(events.len(), 1);
7981 Event::PaymentClaimable { ref purpose, .. } => {
7983 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
7984 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
7986 _ => panic!("expected PaymentPurpose::InvoicePayment")
7989 _ => panic!("Unexpected event"),
7994 #[allow(deprecated)]
7995 fn test_secret_timeout() {
7996 // Simple test of payment secret storage time outs. After
7997 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
7998 let chanmon_cfgs = create_chanmon_cfgs(2);
7999 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8000 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8001 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8003 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8005 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8007 // We should fail to register the same payment hash twice, at least until we've connected a
8008 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8009 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8010 assert_eq!(err, "Duplicate payment hash");
8011 } else { panic!(); }
8013 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8015 header: BlockHeader {
8017 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8018 merkle_root: TxMerkleNode::all_zeros(),
8019 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8023 connect_block(&nodes[1], &block);
8024 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8025 assert_eq!(err, "Duplicate payment hash");
8026 } else { panic!(); }
8028 // If we then connect the second block, we should be able to register the same payment hash
8029 // again (this time getting a new payment secret).
8030 block.header.prev_blockhash = block.header.block_hash();
8031 block.header.time += 1;
8032 connect_block(&nodes[1], &block);
8033 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8034 assert_ne!(payment_secret_1, our_payment_secret);
8037 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8038 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8039 check_added_monitors!(nodes[0], 1);
8040 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8041 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8042 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8043 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8045 // Note that after leaving the above scope we have no knowledge of any arguments or return
8046 // values from previous calls.
8047 expect_pending_htlcs_forwardable!(nodes[1]);
8048 let events = nodes[1].node.get_and_clear_pending_events();
8049 assert_eq!(events.len(), 1);
8051 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8052 assert!(payment_preimage.is_none());
8053 assert_eq!(payment_secret, our_payment_secret);
8054 // We don't actually have the payment preimage with which to claim this payment!
8056 _ => panic!("Unexpected event"),
8061 fn test_bad_secret_hash() {
8062 // Simple test of unregistered payment hash/invalid payment secret handling
8063 let chanmon_cfgs = create_chanmon_cfgs(2);
8064 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8065 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8066 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8068 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8070 let random_payment_hash = PaymentHash([42; 32]);
8071 let random_payment_secret = PaymentSecret([43; 32]);
8072 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8073 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8075 // All the below cases should end up being handled exactly identically, so we macro the
8076 // resulting events.
8077 macro_rules! handle_unknown_invalid_payment_data {
8078 ($payment_hash: expr) => {
8079 check_added_monitors!(nodes[0], 1);
8080 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8081 let payment_event = SendEvent::from_event(events.pop().unwrap());
8082 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8083 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8085 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8086 // again to process the pending backwards-failure of the HTLC
8087 expect_pending_htlcs_forwardable!(nodes[1]);
8088 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8089 check_added_monitors!(nodes[1], 1);
8091 // We should fail the payment back
8092 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8093 match events.pop().unwrap() {
8094 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8095 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8096 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8098 _ => panic!("Unexpected event"),
8103 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8104 // Error data is the HTLC value (100,000) and current block height
8105 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8107 // Send a payment with the right payment hash but the wrong payment secret
8108 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8109 handle_unknown_invalid_payment_data!(our_payment_hash);
8110 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8112 // Send a payment with a random payment hash, but the right payment secret
8113 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8114 handle_unknown_invalid_payment_data!(random_payment_hash);
8115 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8117 // Send a payment with a random payment hash and random payment secret
8118 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8119 handle_unknown_invalid_payment_data!(random_payment_hash);
8120 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8124 fn test_update_err_monitor_lockdown() {
8125 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8126 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8127 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8130 // This scenario may happen in a watchtower setup, where watchtower process a block height
8131 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8132 // commitment at same time.
8134 let chanmon_cfgs = create_chanmon_cfgs(2);
8135 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8136 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8137 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8139 // Create some initial channel
8140 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8141 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8143 // Rebalance the network to generate htlc in the two directions
8144 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8146 // Route a HTLC from node 0 to node 1 (but don't settle)
8147 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8149 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8150 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8151 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8152 let persister = test_utils::TestPersister::new();
8155 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8156 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8157 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8158 assert!(new_monitor == *monitor);
8161 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);
8162 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8165 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8166 let block = Block { header, txdata: vec![] };
8167 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8168 // transaction lock time requirements here.
8169 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8170 watchtower.chain_monitor.block_connected(&block, 200);
8172 // Try to update ChannelMonitor
8173 nodes[1].node.claim_funds(preimage);
8174 check_added_monitors!(nodes[1], 1);
8175 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8177 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8178 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8179 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8181 let mut node_0_per_peer_lock;
8182 let mut node_0_peer_state_lock;
8183 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8184 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8185 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8186 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8187 } else { assert!(false); }
8189 // Our local monitor is in-sync and hasn't processed yet timeout
8190 check_added_monitors!(nodes[0], 1);
8191 let events = nodes[0].node.get_and_clear_pending_events();
8192 assert_eq!(events.len(), 1);
8196 fn test_concurrent_monitor_claim() {
8197 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8198 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8199 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8200 // state N+1 confirms. Alice claims output from state N+1.
8202 let chanmon_cfgs = create_chanmon_cfgs(2);
8203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8205 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8207 // Create some initial channel
8208 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8209 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8211 // Rebalance the network to generate htlc in the two directions
8212 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8214 // Route a HTLC from node 0 to node 1 (but don't settle)
8215 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8217 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8218 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8219 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8220 let persister = test_utils::TestPersister::new();
8221 let watchtower_alice = {
8223 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8224 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8225 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8226 assert!(new_monitor == *monitor);
8229 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);
8230 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8233 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8234 let block = Block { header, txdata: vec![] };
8235 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8236 // transaction lock time requirements here.
8237 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));
8238 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8240 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8242 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8243 assert_eq!(txn.len(), 2);
8247 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8248 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8249 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8250 let persister = test_utils::TestPersister::new();
8251 let watchtower_bob = {
8253 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8254 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8255 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8256 assert!(new_monitor == *monitor);
8259 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);
8260 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8263 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8264 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8266 // Route another payment to generate another update with still previous HTLC pending
8267 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8269 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
8271 check_added_monitors!(nodes[1], 1);
8273 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8274 assert_eq!(updates.update_add_htlcs.len(), 1);
8275 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8277 let mut node_0_per_peer_lock;
8278 let mut node_0_peer_state_lock;
8279 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8280 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8281 // Watchtower Alice should already have seen the block and reject the update
8282 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8283 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8284 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8285 } else { assert!(false); }
8287 // Our local monitor is in-sync and hasn't processed yet timeout
8288 check_added_monitors!(nodes[0], 1);
8290 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8291 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8292 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8294 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8297 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8298 assert_eq!(txn.len(), 2);
8299 bob_state_y = txn[0].clone();
8303 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8304 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8305 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);
8307 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8308 assert_eq!(htlc_txn.len(), 1);
8309 check_spends!(htlc_txn[0], bob_state_y);
8314 fn test_pre_lockin_no_chan_closed_update() {
8315 // Test that if a peer closes a channel in response to a funding_created message we don't
8316 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8319 // Doing so would imply a channel monitor update before the initial channel monitor
8320 // registration, violating our API guarantees.
8322 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8323 // then opening a second channel with the same funding output as the first (which is not
8324 // rejected because the first channel does not exist in the ChannelManager) and closing it
8325 // before receiving funding_signed.
8326 let chanmon_cfgs = create_chanmon_cfgs(2);
8327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8329 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8331 // Create an initial channel
8332 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8333 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8334 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8335 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8336 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8338 // Move the first channel through the funding flow...
8339 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8341 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8342 check_added_monitors!(nodes[0], 0);
8344 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8345 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8346 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8347 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8348 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8352 fn test_htlc_no_detection() {
8353 // This test is a mutation to underscore the detection logic bug we had
8354 // before #653. HTLC value routed is above the remaining balance, thus
8355 // inverting HTLC and `to_remote` output. HTLC will come second and
8356 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8357 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8358 // outputs order detection for correct spending children filtring.
8360 let chanmon_cfgs = create_chanmon_cfgs(2);
8361 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8362 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8363 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8365 // Create some initial channels
8366 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8368 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8369 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8370 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8371 assert_eq!(local_txn[0].input.len(), 1);
8372 assert_eq!(local_txn[0].output.len(), 3);
8373 check_spends!(local_txn[0], chan_1.3);
8375 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8376 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8377 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8378 // We deliberately connect the local tx twice as this should provoke a failure calling
8379 // this test before #653 fix.
8380 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);
8381 check_closed_broadcast!(nodes[0], true);
8382 check_added_monitors!(nodes[0], 1);
8383 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8384 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8386 let htlc_timeout = {
8387 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8388 assert_eq!(node_txn.len(), 1);
8389 assert_eq!(node_txn[0].input.len(), 1);
8390 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8391 check_spends!(node_txn[0], local_txn[0]);
8395 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8396 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8397 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8398 expect_payment_failed!(nodes[0], our_payment_hash, false);
8401 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8402 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8403 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8404 // Carol, Alice would be the upstream node, and Carol the downstream.)
8406 // Steps of the test:
8407 // 1) Alice sends a HTLC to Carol through Bob.
8408 // 2) Carol doesn't settle the HTLC.
8409 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8410 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8411 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8412 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8413 // 5) Carol release the preimage to Bob off-chain.
8414 // 6) Bob claims the offered output on the broadcasted commitment.
8415 let chanmon_cfgs = create_chanmon_cfgs(3);
8416 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8417 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8418 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8420 // Create some initial channels
8421 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8422 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8424 // Steps (1) and (2):
8425 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8426 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8428 // Check that Alice's commitment transaction now contains an output for this HTLC.
8429 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8430 check_spends!(alice_txn[0], chan_ab.3);
8431 assert_eq!(alice_txn[0].output.len(), 2);
8432 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8433 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8434 assert_eq!(alice_txn.len(), 2);
8436 // Steps (3) and (4):
8437 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8438 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8439 let mut force_closing_node = 0; // Alice force-closes
8440 let mut counterparty_node = 1; // Bob if Alice force-closes
8443 if !broadcast_alice {
8444 force_closing_node = 1;
8445 counterparty_node = 0;
8447 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8448 check_closed_broadcast!(nodes[force_closing_node], true);
8449 check_added_monitors!(nodes[force_closing_node], 1);
8450 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8451 if go_onchain_before_fulfill {
8452 let txn_to_broadcast = match broadcast_alice {
8453 true => alice_txn.clone(),
8454 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8456 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8457 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8458 if broadcast_alice {
8459 check_closed_broadcast!(nodes[1], true);
8460 check_added_monitors!(nodes[1], 1);
8461 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8466 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8467 // process of removing the HTLC from their commitment transactions.
8468 nodes[2].node.claim_funds(payment_preimage);
8469 check_added_monitors!(nodes[2], 1);
8470 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8472 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8473 assert!(carol_updates.update_add_htlcs.is_empty());
8474 assert!(carol_updates.update_fail_htlcs.is_empty());
8475 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8476 assert!(carol_updates.update_fee.is_none());
8477 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8479 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8480 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8481 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8482 if !go_onchain_before_fulfill && broadcast_alice {
8483 let events = nodes[1].node.get_and_clear_pending_msg_events();
8484 assert_eq!(events.len(), 1);
8486 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8487 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8489 _ => panic!("Unexpected event"),
8492 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8493 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8494 // Carol<->Bob's updated commitment transaction info.
8495 check_added_monitors!(nodes[1], 2);
8497 let events = nodes[1].node.get_and_clear_pending_msg_events();
8498 assert_eq!(events.len(), 2);
8499 let bob_revocation = match events[0] {
8500 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8501 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8504 _ => panic!("Unexpected event"),
8506 let bob_updates = match events[1] {
8507 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8508 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8511 _ => panic!("Unexpected event"),
8514 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8515 check_added_monitors!(nodes[2], 1);
8516 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8517 check_added_monitors!(nodes[2], 1);
8519 let events = nodes[2].node.get_and_clear_pending_msg_events();
8520 assert_eq!(events.len(), 1);
8521 let carol_revocation = match events[0] {
8522 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8523 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8526 _ => panic!("Unexpected event"),
8528 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8529 check_added_monitors!(nodes[1], 1);
8531 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8532 // here's where we put said channel's commitment tx on-chain.
8533 let mut txn_to_broadcast = alice_txn.clone();
8534 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8535 if !go_onchain_before_fulfill {
8536 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8537 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8538 // If Bob was the one to force-close, he will have already passed these checks earlier.
8539 if broadcast_alice {
8540 check_closed_broadcast!(nodes[1], true);
8541 check_added_monitors!(nodes[1], 1);
8542 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8544 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8545 if broadcast_alice {
8546 assert_eq!(bob_txn.len(), 1);
8547 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8549 assert_eq!(bob_txn.len(), 2);
8550 check_spends!(bob_txn[0], chan_ab.3);
8555 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8556 // broadcasted commitment transaction.
8558 let script_weight = match broadcast_alice {
8559 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8560 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8562 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8563 // Bob force-closed and broadcasts the commitment transaction along with a
8564 // HTLC-output-claiming transaction.
8565 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8566 if broadcast_alice {
8567 assert_eq!(bob_txn.len(), 1);
8568 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8569 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8571 assert_eq!(bob_txn.len(), 2);
8572 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8573 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8579 fn test_onchain_htlc_settlement_after_close() {
8580 do_test_onchain_htlc_settlement_after_close(true, true);
8581 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8582 do_test_onchain_htlc_settlement_after_close(true, false);
8583 do_test_onchain_htlc_settlement_after_close(false, false);
8587 fn test_duplicate_temporary_channel_id_from_different_peers() {
8588 // Tests that we can accept two different `OpenChannel` requests with the same
8589 // `temporary_channel_id`, as long as they are from different peers.
8590 let chanmon_cfgs = create_chanmon_cfgs(3);
8591 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8592 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8593 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8595 // Create an first channel channel
8596 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8597 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8599 // Create an second channel
8600 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8601 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8603 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8604 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8605 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8607 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8608 // `temporary_channel_id` as they are from different peers.
8609 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8611 let events = nodes[0].node.get_and_clear_pending_msg_events();
8612 assert_eq!(events.len(), 1);
8614 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8615 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8616 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8618 _ => panic!("Unexpected event"),
8622 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8624 let events = nodes[0].node.get_and_clear_pending_msg_events();
8625 assert_eq!(events.len(), 1);
8627 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8628 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8629 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8631 _ => panic!("Unexpected event"),
8637 fn test_duplicate_chan_id() {
8638 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8639 // already open we reject it and keep the old channel.
8641 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8642 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8643 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8644 // updating logic for the existing channel.
8645 let chanmon_cfgs = create_chanmon_cfgs(2);
8646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8650 // Create an initial channel
8651 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8652 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8653 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8654 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()));
8656 // Try to create a second channel with the same temporary_channel_id as the first and check
8657 // that it is rejected.
8658 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8660 let events = nodes[1].node.get_and_clear_pending_msg_events();
8661 assert_eq!(events.len(), 1);
8663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8664 // Technically, at this point, nodes[1] would be justified in thinking both the
8665 // first (valid) and second (invalid) channels are closed, given they both have
8666 // the same non-temporary channel_id. However, currently we do not, so we just
8667 // move forward with it.
8668 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8669 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8671 _ => panic!("Unexpected event"),
8675 // Move the first channel through the funding flow...
8676 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8678 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8679 check_added_monitors!(nodes[0], 0);
8681 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8682 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8684 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8685 assert_eq!(added_monitors.len(), 1);
8686 assert_eq!(added_monitors[0].0, funding_output);
8687 added_monitors.clear();
8689 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8691 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8692 let channel_id = funding_outpoint.to_channel_id();
8694 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8697 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8698 // Technically this is allowed by the spec, but we don't support it and there's little reason
8699 // to. Still, it shouldn't cause any other issues.
8700 open_chan_msg.temporary_channel_id = channel_id;
8701 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8703 let events = nodes[1].node.get_and_clear_pending_msg_events();
8704 assert_eq!(events.len(), 1);
8706 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8707 // Technically, at this point, nodes[1] would be justified in thinking both
8708 // channels are closed, but currently we do not, so we just move forward with it.
8709 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8710 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8712 _ => panic!("Unexpected event"),
8716 // Now try to create a second channel which has a duplicate funding output.
8717 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8718 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8719 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8720 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()));
8721 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8723 let funding_created = {
8724 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8725 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8726 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8727 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8728 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8729 // channelmanager in a possibly nonsense state instead).
8730 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8731 let logger = test_utils::TestLogger::new();
8732 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8734 check_added_monitors!(nodes[0], 0);
8735 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8736 // At this point we'll look up if the channel_id is present and immediately fail the channel
8737 // without trying to persist the `ChannelMonitor`.
8738 check_added_monitors!(nodes[1], 0);
8740 // ...still, nodes[1] will reject the duplicate channel.
8742 let events = nodes[1].node.get_and_clear_pending_msg_events();
8743 assert_eq!(events.len(), 1);
8745 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8746 // Technically, at this point, nodes[1] would be justified in thinking both
8747 // channels are closed, but currently we do not, so we just move forward with it.
8748 assert_eq!(msg.channel_id, channel_id);
8749 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8751 _ => panic!("Unexpected event"),
8755 // finally, finish creating the original channel and send a payment over it to make sure
8756 // everything is functional.
8757 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8759 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8760 assert_eq!(added_monitors.len(), 1);
8761 assert_eq!(added_monitors[0].0, funding_output);
8762 added_monitors.clear();
8765 let events_4 = nodes[0].node.get_and_clear_pending_events();
8766 assert_eq!(events_4.len(), 0);
8767 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8768 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8770 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8771 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8772 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8774 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8778 fn test_error_chans_closed() {
8779 // Test that we properly handle error messages, closing appropriate channels.
8781 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8782 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8783 // we can test various edge cases around it to ensure we don't regress.
8784 let chanmon_cfgs = create_chanmon_cfgs(3);
8785 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8786 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8787 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8789 // Create some initial channels
8790 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8791 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8792 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8794 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8795 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8796 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8798 // Closing a channel from a different peer has no effect
8799 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8800 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8802 // Closing one channel doesn't impact others
8803 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8804 check_added_monitors!(nodes[0], 1);
8805 check_closed_broadcast!(nodes[0], false);
8806 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8807 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8808 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8809 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);
8810 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);
8812 // A null channel ID should close all channels
8813 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8814 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8815 check_added_monitors!(nodes[0], 2);
8816 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8817 let events = nodes[0].node.get_and_clear_pending_msg_events();
8818 assert_eq!(events.len(), 2);
8820 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8821 assert_eq!(msg.contents.flags & 2, 2);
8823 _ => panic!("Unexpected event"),
8826 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8827 assert_eq!(msg.contents.flags & 2, 2);
8829 _ => panic!("Unexpected event"),
8831 // Note that at this point users of a standard PeerHandler will end up calling
8832 // peer_disconnected.
8833 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8834 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8836 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8837 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8838 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8842 fn test_invalid_funding_tx() {
8843 // Test that we properly handle invalid funding transactions sent to us from a peer.
8845 // Previously, all other major lightning implementations had failed to properly sanitize
8846 // funding transactions from their counterparties, leading to a multi-implementation critical
8847 // security vulnerability (though we always sanitized properly, we've previously had
8848 // un-released crashes in the sanitization process).
8850 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
8851 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
8852 // gave up on it. We test this here by generating such a transaction.
8853 let chanmon_cfgs = create_chanmon_cfgs(2);
8854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8856 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8858 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8859 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()));
8860 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()));
8862 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
8864 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
8865 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
8866 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
8868 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
8869 let wit_program_script: Script = wit_program.into();
8870 for output in tx.output.iter_mut() {
8871 // Make the confirmed funding transaction have a bogus script_pubkey
8872 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
8875 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
8876 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()));
8877 check_added_monitors!(nodes[1], 1);
8879 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()));
8880 check_added_monitors!(nodes[0], 1);
8882 let events_1 = nodes[0].node.get_and_clear_pending_events();
8883 assert_eq!(events_1.len(), 0);
8885 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8886 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8887 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8889 let expected_err = "funding tx had wrong script/value or output index";
8890 confirm_transaction_at(&nodes[1], &tx, 1);
8891 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8892 check_added_monitors!(nodes[1], 1);
8893 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8894 assert_eq!(events_2.len(), 1);
8895 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8896 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8897 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8898 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8899 } else { panic!(); }
8900 } else { panic!(); }
8901 assert_eq!(nodes[1].node.list_channels().len(), 0);
8903 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
8904 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
8905 // as its not 32 bytes long.
8906 let mut spend_tx = Transaction {
8907 version: 2i32, lock_time: PackedLockTime::ZERO,
8908 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
8909 previous_output: BitcoinOutPoint {
8913 script_sig: Script::new(),
8914 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
8915 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
8917 output: vec![TxOut {
8919 script_pubkey: Script::new(),
8922 check_spends!(spend_tx, tx);
8923 mine_transaction(&nodes[1], &spend_tx);
8926 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8927 // In the first version of the chain::Confirm interface, after a refactor was made to not
8928 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8929 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8930 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8931 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8932 // spending transaction until height N+1 (or greater). This was due to the way
8933 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8934 // spending transaction at the height the input transaction was confirmed at, not whether we
8935 // should broadcast a spending transaction at the current height.
8936 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8937 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8938 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8939 // until we learned about an additional block.
8941 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8942 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8943 let chanmon_cfgs = create_chanmon_cfgs(3);
8944 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8945 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8946 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8947 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8949 create_announced_chan_between_nodes(&nodes, 0, 1);
8950 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
8951 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8952 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
8953 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8955 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
8956 check_closed_broadcast!(nodes[1], true);
8957 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8958 check_added_monitors!(nodes[1], 1);
8959 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8960 assert_eq!(node_txn.len(), 1);
8962 let conf_height = nodes[1].best_block_info().1;
8963 if !test_height_before_timelock {
8964 connect_blocks(&nodes[1], 24 * 6);
8966 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8967 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8968 if test_height_before_timelock {
8969 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8970 // generate any events or broadcast any transactions
8971 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8972 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
8974 // We should broadcast an HTLC transaction spending our funding transaction first
8975 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8976 assert_eq!(spending_txn.len(), 2);
8977 assert_eq!(spending_txn[0], node_txn[0]);
8978 check_spends!(spending_txn[1], node_txn[0]);
8979 // We should also generate a SpendableOutputs event with the to_self output (as its
8981 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
8982 assert_eq!(descriptor_spend_txn.len(), 1);
8984 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
8985 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
8986 // additional block built on top of the current chain.
8987 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8988 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
8989 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 }]);
8990 check_added_monitors!(nodes[1], 1);
8992 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8993 assert!(updates.update_add_htlcs.is_empty());
8994 assert!(updates.update_fulfill_htlcs.is_empty());
8995 assert_eq!(updates.update_fail_htlcs.len(), 1);
8996 assert!(updates.update_fail_malformed_htlcs.is_empty());
8997 assert!(updates.update_fee.is_none());
8998 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
8999 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9000 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9005 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9006 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9007 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9010 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9011 let chanmon_cfgs = create_chanmon_cfgs(2);
9012 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9013 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9014 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9016 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9018 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9019 .with_features(nodes[1].node.invoice_features());
9020 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9022 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9025 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9026 check_added_monitors!(nodes[0], 1);
9027 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9028 assert_eq!(events.len(), 1);
9029 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9030 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9031 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9033 expect_pending_htlcs_forwardable!(nodes[1]);
9034 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9037 // Note that we use a different PaymentId here to allow us to duplicativly pay
9038 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9039 check_added_monitors!(nodes[0], 1);
9040 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9041 assert_eq!(events.len(), 1);
9042 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9044 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9045 // At this point, nodes[1] would notice it has too much value for the payment. It will
9046 // assume the second is a privacy attack (no longer particularly relevant
9047 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9048 // the first HTLC delivered above.
9051 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9052 nodes[1].node.process_pending_htlc_forwards();
9054 if test_for_second_fail_panic {
9055 // Now we go fail back the first HTLC from the user end.
9056 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9058 let expected_destinations = vec![
9059 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9060 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9062 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9063 nodes[1].node.process_pending_htlc_forwards();
9065 check_added_monitors!(nodes[1], 1);
9066 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9067 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9069 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9070 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9071 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9073 let failure_events = nodes[0].node.get_and_clear_pending_events();
9074 assert_eq!(failure_events.len(), 4);
9075 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9076 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9077 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9078 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9080 // Let the second HTLC fail and claim the first
9081 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9082 nodes[1].node.process_pending_htlc_forwards();
9084 check_added_monitors!(nodes[1], 1);
9085 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9086 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9087 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9089 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9091 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9096 fn test_dup_htlc_second_fail_panic() {
9097 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9098 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9099 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9100 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9101 do_test_dup_htlc_second_rejected(true);
9105 fn test_dup_htlc_second_rejected() {
9106 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9107 // simply reject the second HTLC but are still able to claim the first HTLC.
9108 do_test_dup_htlc_second_rejected(false);
9112 fn test_inconsistent_mpp_params() {
9113 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9114 // such HTLC and allow the second to stay.
9115 let chanmon_cfgs = create_chanmon_cfgs(4);
9116 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9117 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9118 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9120 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9121 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9122 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9123 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9125 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9126 .with_features(nodes[3].node.invoice_features());
9127 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9128 assert_eq!(route.paths.len(), 2);
9129 route.paths.sort_by(|path_a, _| {
9130 // Sort the path so that the path through nodes[1] comes first
9131 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9132 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9135 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9137 let cur_height = nodes[0].best_block_info().1;
9138 let payment_id = PaymentId([42; 32]);
9140 let session_privs = {
9141 // We create a fake route here so that we start with three pending HTLCs, which we'll
9142 // ultimately have, just not right away.
9143 let mut dup_route = route.clone();
9144 dup_route.paths.push(route.paths[1].clone());
9145 nodes[0].node.test_add_new_pending_payment(our_payment_hash, Some(our_payment_secret), payment_id, &dup_route).unwrap()
9147 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();
9148 check_added_monitors!(nodes[0], 1);
9151 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9152 assert_eq!(events.len(), 1);
9153 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9155 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9157 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();
9158 check_added_monitors!(nodes[0], 1);
9161 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9162 assert_eq!(events.len(), 1);
9163 let payment_event = SendEvent::from_event(events.pop().unwrap());
9165 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9166 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9168 expect_pending_htlcs_forwardable!(nodes[2]);
9169 check_added_monitors!(nodes[2], 1);
9171 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9172 assert_eq!(events.len(), 1);
9173 let payment_event = SendEvent::from_event(events.pop().unwrap());
9175 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9176 check_added_monitors!(nodes[3], 0);
9177 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9179 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9180 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9181 // post-payment_secrets) and fail back the new HTLC.
9183 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9184 nodes[3].node.process_pending_htlc_forwards();
9185 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9186 nodes[3].node.process_pending_htlc_forwards();
9188 check_added_monitors!(nodes[3], 1);
9190 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9191 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9192 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9194 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 }]);
9195 check_added_monitors!(nodes[2], 1);
9197 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9198 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9199 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9201 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9203 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();
9204 check_added_monitors!(nodes[0], 1);
9206 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9207 assert_eq!(events.len(), 1);
9208 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9210 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9211 let events = nodes[0].node.get_and_clear_pending_events();
9212 assert_eq!(events.len(), 3);
9214 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9215 assert_eq!(payment_hash, our_payment_hash);
9217 _ => panic!("Unexpected event")
9220 Event::PaymentPathSuccessful { payment_hash, .. } => {
9221 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9223 _ => panic!("Unexpected event")
9226 Event::PaymentPathSuccessful { payment_hash, .. } => {
9227 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9229 _ => panic!("Unexpected event")
9234 fn test_keysend_payments_to_public_node() {
9235 let chanmon_cfgs = create_chanmon_cfgs(2);
9236 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9237 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9238 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9240 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9241 let network_graph = nodes[0].network_graph.clone();
9242 let payer_pubkey = nodes[0].node.get_our_node_id();
9243 let payee_pubkey = nodes[1].node.get_our_node_id();
9244 let route_params = RouteParameters {
9245 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9246 final_value_msat: 10000,
9248 let scorer = test_utils::TestScorer::new();
9249 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9250 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9252 let test_preimage = PaymentPreimage([42; 32]);
9253 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9254 check_added_monitors!(nodes[0], 1);
9255 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9256 assert_eq!(events.len(), 1);
9257 let event = events.pop().unwrap();
9258 let path = vec![&nodes[1]];
9259 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9260 claim_payment(&nodes[0], &path, test_preimage);
9264 fn test_keysend_payments_to_private_node() {
9265 let chanmon_cfgs = create_chanmon_cfgs(2);
9266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9270 let payer_pubkey = nodes[0].node.get_our_node_id();
9271 let payee_pubkey = nodes[1].node.get_our_node_id();
9273 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9274 let route_params = RouteParameters {
9275 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9276 final_value_msat: 10000,
9278 let network_graph = nodes[0].network_graph.clone();
9279 let first_hops = nodes[0].node.list_usable_channels();
9280 let scorer = test_utils::TestScorer::new();
9281 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9282 let route = find_route(
9283 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9284 nodes[0].logger, &scorer, &random_seed_bytes
9287 let test_preimage = PaymentPreimage([42; 32]);
9288 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage), PaymentId(test_preimage.0)).unwrap();
9289 check_added_monitors!(nodes[0], 1);
9290 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9291 assert_eq!(events.len(), 1);
9292 let event = events.pop().unwrap();
9293 let path = vec![&nodes[1]];
9294 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9295 claim_payment(&nodes[0], &path, test_preimage);
9299 fn test_double_partial_claim() {
9300 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9301 // time out, the sender resends only some of the MPP parts, then the user processes the
9302 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9304 let chanmon_cfgs = create_chanmon_cfgs(4);
9305 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9306 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9307 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9309 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9310 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9311 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9312 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9314 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9315 assert_eq!(route.paths.len(), 2);
9316 route.paths.sort_by(|path_a, _| {
9317 // Sort the path so that the path through nodes[1] comes first
9318 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9319 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9322 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9323 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9324 // amount of time to respond to.
9326 // Connect some blocks to time out the payment
9327 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9328 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9330 let failed_destinations = vec![
9331 HTLCDestination::FailedPayment { payment_hash },
9332 HTLCDestination::FailedPayment { payment_hash },
9334 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9336 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9338 // nodes[1] now retries one of the two paths...
9339 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9340 check_added_monitors!(nodes[0], 2);
9342 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9343 assert_eq!(events.len(), 2);
9344 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9345 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9347 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9348 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9349 nodes[3].node.claim_funds(payment_preimage);
9350 check_added_monitors!(nodes[3], 0);
9351 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9354 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9355 #[derive(Clone, Copy, PartialEq)]
9356 enum ExposureEvent {
9357 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9359 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9361 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9362 AtUpdateFeeOutbound,
9365 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9366 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9369 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9370 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9371 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9372 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9373 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9374 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9375 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9376 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9378 let chanmon_cfgs = create_chanmon_cfgs(2);
9379 let mut config = test_default_channel_config();
9380 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9381 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9382 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9383 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9385 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9386 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9387 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9388 open_channel.max_accepted_htlcs = 60;
9390 open_channel.dust_limit_satoshis = 546;
9392 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9393 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9394 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9396 let opt_anchors = false;
9398 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9401 let mut node_0_per_peer_lock;
9402 let mut node_0_peer_state_lock;
9403 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9404 chan.holder_dust_limit_satoshis = 546;
9407 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9408 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()));
9409 check_added_monitors!(nodes[1], 1);
9411 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()));
9412 check_added_monitors!(nodes[0], 1);
9414 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9415 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9416 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9418 let dust_buffer_feerate = {
9419 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9420 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9421 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9422 chan.get_dust_buffer_feerate(None) as u64
9424 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;
9425 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9427 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;
9428 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9430 let dust_htlc_on_counterparty_tx: u64 = 25;
9431 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9434 if dust_outbound_balance {
9435 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9436 // Outbound dust balance: 4372 sats
9437 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9438 for i in 0..dust_outbound_htlc_on_holder_tx {
9439 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9440 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); }
9443 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9444 // Inbound dust balance: 4372 sats
9445 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9446 for _ in 0..dust_inbound_htlc_on_holder_tx {
9447 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9451 if dust_outbound_balance {
9452 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9453 // Outbound dust balance: 5000 sats
9454 for i in 0..dust_htlc_on_counterparty_tx {
9455 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9456 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); }
9459 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9460 // Inbound dust balance: 5000 sats
9461 for _ in 0..dust_htlc_on_counterparty_tx {
9462 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9467 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9468 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9469 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 });
9470 let mut config = UserConfig::default();
9471 // With default dust exposure: 5000 sats
9473 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9474 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9475 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)));
9477 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)));
9479 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9480 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 });
9481 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9482 check_added_monitors!(nodes[1], 1);
9483 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9484 assert_eq!(events.len(), 1);
9485 let payment_event = SendEvent::from_event(events.remove(0));
9486 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9487 // With default dust exposure: 5000 sats
9489 // Outbound dust balance: 6399 sats
9490 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9491 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9492 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);
9494 // Outbound dust balance: 5200 sats
9495 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);
9497 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9498 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9499 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", ); }
9501 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9502 *feerate_lock = *feerate_lock * 10;
9504 nodes[0].node.timer_tick_occurred();
9505 check_added_monitors!(nodes[0], 1);
9506 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9509 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9510 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9511 added_monitors.clear();
9515 fn test_max_dust_htlc_exposure() {
9516 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9517 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9518 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9519 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9520 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9521 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9522 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9523 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9524 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9525 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9526 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9527 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9531 fn test_non_final_funding_tx() {
9532 let chanmon_cfgs = create_chanmon_cfgs(2);
9533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9535 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9537 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9538 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9539 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9540 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9541 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9543 let best_height = nodes[0].node.best_block.read().unwrap().height();
9545 let chan_id = *nodes[0].network_chan_count.borrow();
9546 let events = nodes[0].node.get_and_clear_pending_events();
9547 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9548 assert_eq!(events.len(), 1);
9549 let mut tx = match events[0] {
9550 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9551 // Timelock the transaction _beyond_ the best client height + 2.
9552 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9553 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9556 _ => panic!("Unexpected event"),
9558 // Transaction should fail as it's evaluated as non-final for propagation.
9559 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9560 Err(APIError::APIMisuseError { err }) => {
9561 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9566 // However, transaction should be accepted if it's in a +2 headroom from best block.
9567 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9568 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9569 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9573 fn accept_busted_but_better_fee() {
9574 // If a peer sends us a fee update that is too low, but higher than our previous channel
9575 // feerate, we should accept it. In the future we may want to consider closing the channel
9576 // later, but for now we only accept the update.
9577 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9580 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9582 create_chan_between_nodes(&nodes[0], &nodes[1]);
9584 // Set nodes[1] to expect 5,000 sat/kW.
9586 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9587 *feerate_lock = 5000;
9590 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9592 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9593 *feerate_lock = 1000;
9595 nodes[0].node.timer_tick_occurred();
9596 check_added_monitors!(nodes[0], 1);
9598 let events = nodes[0].node.get_and_clear_pending_msg_events();
9599 assert_eq!(events.len(), 1);
9601 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9602 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9603 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9605 _ => panic!("Unexpected event"),
9608 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9611 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9612 *feerate_lock = 2000;
9614 nodes[0].node.timer_tick_occurred();
9615 check_added_monitors!(nodes[0], 1);
9617 let events = nodes[0].node.get_and_clear_pending_msg_events();
9618 assert_eq!(events.len(), 1);
9620 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9621 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9622 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9624 _ => panic!("Unexpected event"),
9627 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9630 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9631 *feerate_lock = 1000;
9633 nodes[0].node.timer_tick_occurred();
9634 check_added_monitors!(nodes[0], 1);
9636 let events = nodes[0].node.get_and_clear_pending_msg_events();
9637 assert_eq!(events.len(), 1);
9639 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9640 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9641 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9642 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9643 check_closed_broadcast!(nodes[1], true);
9644 check_added_monitors!(nodes[1], 1);
9646 _ => panic!("Unexpected event"),
9650 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9651 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9654 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9655 let min_final_cltv_expiry_delta = 120;
9656 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9657 min_final_cltv_expiry_delta - 2 };
9658 let recv_value = 100_000;
9660 create_chan_between_nodes(&nodes[0], &nodes[1]);
9662 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9663 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9664 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9665 Some(recv_value), Some(min_final_cltv_expiry_delta));
9666 (payment_hash, payment_preimage, payment_secret)
9668 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9669 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9671 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9672 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret), PaymentId(payment_hash.0)).unwrap();
9673 check_added_monitors!(nodes[0], 1);
9674 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9675 assert_eq!(events.len(), 1);
9676 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9677 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9678 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9679 expect_pending_htlcs_forwardable!(nodes[1]);
9682 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9683 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9685 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9687 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9689 check_added_monitors!(nodes[1], 1);
9691 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9692 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9693 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9695 expect_payment_failed!(nodes[0], payment_hash, true);
9700 fn test_payment_with_custom_min_cltv_expiry_delta() {
9701 do_payment_with_custom_min_final_cltv_expiry(false, false);
9702 do_payment_with_custom_min_final_cltv_expiry(false, true);
9703 do_payment_with_custom_min_final_cltv_expiry(true, false);
9704 do_payment_with_custom_min_final_cltv_expiry(true, true);