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, RecipientOnionFields, 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_with_route(&route, our_payment_hash,
261 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
262 check_added_monitors!(nodes[1], 1);
264 let payment_event = {
265 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
266 assert_eq!(events_1.len(), 1);
267 SendEvent::from_event(events_1.remove(0))
269 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
270 assert_eq!(payment_event.msgs.len(), 1);
272 // ...now when the messages get delivered everyone should be happy
273 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
274 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
275 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
276 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
277 check_added_monitors!(nodes[0], 1);
279 // deliver(1), generate (3):
280 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
281 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
282 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
283 check_added_monitors!(nodes[1], 1);
285 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
286 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
287 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
290 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
291 assert!(bs_update.update_fee.is_none()); // (4)
292 check_added_monitors!(nodes[1], 1);
294 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
295 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
296 assert!(as_update.update_add_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
299 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
300 assert!(as_update.update_fee.is_none()); // (5)
301 check_added_monitors!(nodes[0], 1);
303 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
304 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
305 // only (6) so get_event_msg's assert(len == 1) passes
306 check_added_monitors!(nodes[0], 1);
308 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
309 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
310 check_added_monitors!(nodes[1], 1);
312 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
313 check_added_monitors!(nodes[0], 1);
315 let events_2 = nodes[0].node.get_and_clear_pending_events();
316 assert_eq!(events_2.len(), 1);
318 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
319 _ => panic!("Unexpected event"),
322 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
323 check_added_monitors!(nodes[1], 1);
327 fn test_update_fee_unordered_raa() {
328 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
329 // crash in an earlier version of the update_fee patch)
330 let chanmon_cfgs = create_chanmon_cfgs(2);
331 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
332 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
333 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
334 create_announced_chan_between_nodes(&nodes, 0, 1);
337 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
339 // First nodes[0] generates an update_fee
341 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
344 nodes[0].node.timer_tick_occurred();
345 check_added_monitors!(nodes[0], 1);
347 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
348 assert_eq!(events_0.len(), 1);
349 let update_msg = match events_0[0] { // (1)
350 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
353 _ => panic!("Unexpected event"),
356 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
358 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
359 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
360 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
361 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
362 check_added_monitors!(nodes[1], 1);
364 let payment_event = {
365 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
366 assert_eq!(events_1.len(), 1);
367 SendEvent::from_event(events_1.remove(0))
369 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
370 assert_eq!(payment_event.msgs.len(), 1);
372 // ...now when the messages get delivered everyone should be happy
373 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
374 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
375 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
376 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
377 check_added_monitors!(nodes[0], 1);
379 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
380 check_added_monitors!(nodes[1], 1);
382 // We can't continue, sadly, because our (1) now has a bogus signature
386 fn test_multi_flight_update_fee() {
387 let chanmon_cfgs = create_chanmon_cfgs(2);
388 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
389 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
390 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
391 create_announced_chan_between_nodes(&nodes, 0, 1);
394 // update_fee/commitment_signed ->
395 // .- send (1) RAA and (2) commitment_signed
396 // update_fee (never committed) ->
398 // We have to manually generate the above update_fee, it is allowed by the protocol but we
399 // don't track which updates correspond to which revoke_and_ack responses so we're in
400 // AwaitingRAA mode and will not generate the update_fee yet.
401 // <- (1) RAA delivered
402 // (3) is generated and send (4) CS -.
403 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
404 // know the per_commitment_point to use for it.
405 // <- (2) commitment_signed delivered
407 // B should send no response here
408 // (4) commitment_signed delivered ->
409 // <- RAA/commitment_signed delivered
412 // First nodes[0] generates an update_fee
415 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
416 initial_feerate = *feerate_lock;
417 *feerate_lock = initial_feerate + 20;
419 nodes[0].node.timer_tick_occurred();
420 check_added_monitors!(nodes[0], 1);
422 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
423 assert_eq!(events_0.len(), 1);
424 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
425 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
426 (update_fee.as_ref().unwrap(), commitment_signed)
428 _ => panic!("Unexpected event"),
431 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
432 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
433 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
434 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
435 check_added_monitors!(nodes[1], 1);
437 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
440 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
441 *feerate_lock = initial_feerate + 40;
443 nodes[0].node.timer_tick_occurred();
444 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
445 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
447 // Create the (3) update_fee message that nodes[0] will generate before it does...
448 let mut update_msg_2 = msgs::UpdateFee {
449 channel_id: update_msg_1.channel_id.clone(),
450 feerate_per_kw: (initial_feerate + 30) as u32,
453 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
455 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
457 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
459 // Deliver (1), generating (3) and (4)
460 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
461 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
462 check_added_monitors!(nodes[0], 1);
463 assert!(as_second_update.update_add_htlcs.is_empty());
464 assert!(as_second_update.update_fulfill_htlcs.is_empty());
465 assert!(as_second_update.update_fail_htlcs.is_empty());
466 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
467 // Check that the update_fee newly generated matches what we delivered:
468 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
469 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
471 // Deliver (2) commitment_signed
472 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
473 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
474 check_added_monitors!(nodes[0], 1);
475 // No commitment_signed so get_event_msg's assert(len == 1) passes
477 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
478 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
479 check_added_monitors!(nodes[1], 1);
482 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
483 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
484 check_added_monitors!(nodes[1], 1);
486 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
487 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
488 check_added_monitors!(nodes[0], 1);
490 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
491 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
492 // No commitment_signed so get_event_msg's assert(len == 1) passes
493 check_added_monitors!(nodes[0], 1);
495 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
496 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
497 check_added_monitors!(nodes[1], 1);
500 fn do_test_sanity_on_in_flight_opens(steps: u8) {
501 // Previously, we had issues deserializing channels when we hadn't connected the first block
502 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
503 // serialization round-trips and simply do steps towards opening a channel and then drop the
506 let chanmon_cfgs = create_chanmon_cfgs(2);
507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
511 if steps & 0b1000_0000 != 0{
513 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
516 connect_block(&nodes[0], &block);
517 connect_block(&nodes[1], &block);
520 if steps & 0x0f == 0 { return; }
521 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
522 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
524 if steps & 0x0f == 1 { return; }
525 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
526 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
528 if steps & 0x0f == 2 { return; }
529 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
531 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
533 if steps & 0x0f == 3 { return; }
534 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
535 check_added_monitors!(nodes[0], 0);
536 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
538 if steps & 0x0f == 4 { return; }
539 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
541 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
542 assert_eq!(added_monitors.len(), 1);
543 assert_eq!(added_monitors[0].0, funding_output);
544 added_monitors.clear();
546 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
548 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
550 if steps & 0x0f == 5 { return; }
551 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
553 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
554 assert_eq!(added_monitors.len(), 1);
555 assert_eq!(added_monitors[0].0, funding_output);
556 added_monitors.clear();
559 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
560 let events_4 = nodes[0].node.get_and_clear_pending_events();
561 assert_eq!(events_4.len(), 0);
563 if steps & 0x0f == 6 { return; }
564 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
566 if steps & 0x0f == 7 { return; }
567 confirm_transaction_at(&nodes[0], &tx, 2);
568 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
569 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
570 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
574 fn test_sanity_on_in_flight_opens() {
575 do_test_sanity_on_in_flight_opens(0);
576 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(1);
578 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(2);
580 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(3);
582 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(4);
584 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(5);
586 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(6);
588 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
589 do_test_sanity_on_in_flight_opens(7);
590 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
591 do_test_sanity_on_in_flight_opens(8);
592 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
596 fn test_update_fee_vanilla() {
597 let chanmon_cfgs = create_chanmon_cfgs(2);
598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
600 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
601 create_announced_chan_between_nodes(&nodes, 0, 1);
604 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
607 nodes[0].node.timer_tick_occurred();
608 check_added_monitors!(nodes[0], 1);
610 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
611 assert_eq!(events_0.len(), 1);
612 let (update_msg, commitment_signed) = match events_0[0] {
613 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 } } => {
614 (update_fee.as_ref(), commitment_signed)
616 _ => panic!("Unexpected event"),
618 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
620 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
621 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
622 check_added_monitors!(nodes[1], 1);
624 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
625 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
626 check_added_monitors!(nodes[0], 1);
628 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
629 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
630 // No commitment_signed so get_event_msg's assert(len == 1) passes
631 check_added_monitors!(nodes[0], 1);
633 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
634 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
635 check_added_monitors!(nodes[1], 1);
639 fn test_update_fee_that_funder_cannot_afford() {
640 let chanmon_cfgs = create_chanmon_cfgs(2);
641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
643 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
644 let channel_value = 5000;
646 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
647 let channel_id = chan.2;
648 let secp_ctx = Secp256k1::new();
649 let default_config = UserConfig::default();
650 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
652 let opt_anchors = false;
654 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
655 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
656 // calculate two different feerates here - the expected local limit as well as the expected
658 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;
659 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
661 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
662 *feerate_lock = feerate;
664 nodes[0].node.timer_tick_occurred();
665 check_added_monitors!(nodes[0], 1);
666 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
668 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
670 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
672 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
674 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
676 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
677 assert_eq!(commitment_tx.output.len(), 2);
678 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
679 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
680 actual_fee = channel_value - actual_fee;
681 assert_eq!(total_fee, actual_fee);
685 // Increment the feerate by a small constant, accounting for rounding errors
686 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
689 nodes[0].node.timer_tick_occurred();
690 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
691 check_added_monitors!(nodes[0], 0);
693 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
695 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
696 // needed to sign the new commitment tx and (2) sign the new commitment tx.
697 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
698 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
699 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
700 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
701 let chan_signer = local_chan.get_signer();
702 let pubkeys = chan_signer.pubkeys();
703 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
704 pubkeys.funding_pubkey)
706 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
707 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
708 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
709 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
710 let chan_signer = remote_chan.get_signer();
711 let pubkeys = chan_signer.pubkeys();
712 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
713 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
714 pubkeys.funding_pubkey)
717 // Assemble the set of keys we can use for signatures for our commitment_signed message.
718 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
719 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
722 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
723 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
724 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
725 let local_chan_signer = local_chan.get_signer();
726 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
727 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
728 INITIAL_COMMITMENT_NUMBER - 1,
730 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
731 opt_anchors, local_funding, remote_funding,
732 commit_tx_keys.clone(),
733 non_buffer_feerate + 4,
735 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
737 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
740 let commit_signed_msg = msgs::CommitmentSigned {
743 htlc_signatures: res.1
746 let update_fee = msgs::UpdateFee {
748 feerate_per_kw: non_buffer_feerate + 4,
751 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
753 //While producing the commitment_signed response after handling a received update_fee request the
754 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
755 //Should produce and error.
756 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
757 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
758 check_added_monitors!(nodes[1], 1);
759 check_closed_broadcast!(nodes[1], true);
760 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
764 fn test_update_fee_with_fundee_update_add_htlc() {
765 let chanmon_cfgs = create_chanmon_cfgs(2);
766 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
767 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
768 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
769 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
772 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
775 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
778 nodes[0].node.timer_tick_occurred();
779 check_added_monitors!(nodes[0], 1);
781 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
782 assert_eq!(events_0.len(), 1);
783 let (update_msg, commitment_signed) = match events_0[0] {
784 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
785 (update_fee.as_ref(), commitment_signed)
787 _ => panic!("Unexpected event"),
789 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
790 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
791 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
792 check_added_monitors!(nodes[1], 1);
794 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
796 // nothing happens since node[1] is in AwaitingRemoteRevoke
797 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
798 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
800 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
801 assert_eq!(added_monitors.len(), 0);
802 added_monitors.clear();
804 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
805 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
806 // node[1] has nothing to do
808 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
809 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
810 check_added_monitors!(nodes[0], 1);
812 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
813 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
814 // No commitment_signed so get_event_msg's assert(len == 1) passes
815 check_added_monitors!(nodes[0], 1);
816 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
817 check_added_monitors!(nodes[1], 1);
818 // AwaitingRemoteRevoke ends here
820 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
821 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
822 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
824 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
825 assert_eq!(commitment_update.update_fee.is_none(), true);
827 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
828 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
829 check_added_monitors!(nodes[0], 1);
830 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
832 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
833 check_added_monitors!(nodes[1], 1);
834 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
836 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
837 check_added_monitors!(nodes[1], 1);
838 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
839 // No commitment_signed so get_event_msg's assert(len == 1) passes
841 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
842 check_added_monitors!(nodes[0], 1);
843 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
845 expect_pending_htlcs_forwardable!(nodes[0]);
847 let events = nodes[0].node.get_and_clear_pending_events();
848 assert_eq!(events.len(), 1);
850 Event::PaymentClaimable { .. } => { },
851 _ => panic!("Unexpected event"),
854 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
856 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
857 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
858 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
859 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
860 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
864 fn test_update_fee() {
865 let chanmon_cfgs = create_chanmon_cfgs(2);
866 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
867 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
868 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
869 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
870 let channel_id = chan.2;
873 // (1) update_fee/commitment_signed ->
874 // <- (2) revoke_and_ack
875 // .- send (3) commitment_signed
876 // (4) update_fee/commitment_signed ->
877 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
878 // <- (3) commitment_signed delivered
879 // send (6) revoke_and_ack -.
880 // <- (5) deliver revoke_and_ack
881 // (6) deliver revoke_and_ack ->
882 // .- send (7) commitment_signed in response to (4)
883 // <- (7) deliver commitment_signed
886 // Create and deliver (1)...
889 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
890 feerate = *feerate_lock;
891 *feerate_lock = feerate + 20;
893 nodes[0].node.timer_tick_occurred();
894 check_added_monitors!(nodes[0], 1);
896 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
897 assert_eq!(events_0.len(), 1);
898 let (update_msg, commitment_signed) = match events_0[0] {
899 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 } } => {
900 (update_fee.as_ref(), commitment_signed)
902 _ => panic!("Unexpected event"),
904 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
906 // Generate (2) and (3):
907 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
908 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
909 check_added_monitors!(nodes[1], 1);
912 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
913 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
914 check_added_monitors!(nodes[0], 1);
916 // Create and deliver (4)...
918 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
919 *feerate_lock = feerate + 30;
921 nodes[0].node.timer_tick_occurred();
922 check_added_monitors!(nodes[0], 1);
923 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
924 assert_eq!(events_0.len(), 1);
925 let (update_msg, commitment_signed) = match events_0[0] {
926 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 } } => {
927 (update_fee.as_ref(), commitment_signed)
929 _ => panic!("Unexpected event"),
932 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
934 check_added_monitors!(nodes[1], 1);
936 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
937 // No commitment_signed so get_event_msg's assert(len == 1) passes
939 // Handle (3), creating (6):
940 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
941 check_added_monitors!(nodes[0], 1);
942 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
943 // No commitment_signed so get_event_msg's assert(len == 1) passes
946 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
947 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
948 check_added_monitors!(nodes[0], 1);
950 // Deliver (6), creating (7):
951 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
952 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
953 assert!(commitment_update.update_add_htlcs.is_empty());
954 assert!(commitment_update.update_fulfill_htlcs.is_empty());
955 assert!(commitment_update.update_fail_htlcs.is_empty());
956 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
957 assert!(commitment_update.update_fee.is_none());
958 check_added_monitors!(nodes[1], 1);
961 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
962 check_added_monitors!(nodes[0], 1);
963 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
964 // No commitment_signed so get_event_msg's assert(len == 1) passes
966 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
967 check_added_monitors!(nodes[1], 1);
968 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
970 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
971 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
972 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
973 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
974 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
978 fn fake_network_test() {
979 // Simple test which builds a network of ChannelManagers, connects them to each other, and
980 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
981 let chanmon_cfgs = create_chanmon_cfgs(4);
982 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
983 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
984 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
986 // Create some initial channels
987 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
988 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
989 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
991 // Rebalance the network a bit by relaying one payment through all the channels...
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
994 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
997 // Send some more payments
998 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
999 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1000 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1002 // Test failure packets
1003 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1004 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1006 // Add a new channel that skips 3
1007 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1009 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1010 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1017 // Do some rebalance loop payments, simultaneously
1018 let mut hops = Vec::with_capacity(3);
1019 hops.push(RouteHop {
1020 pubkey: nodes[2].node.get_our_node_id(),
1021 node_features: NodeFeatures::empty(),
1022 short_channel_id: chan_2.0.contents.short_channel_id,
1023 channel_features: ChannelFeatures::empty(),
1025 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1027 hops.push(RouteHop {
1028 pubkey: nodes[3].node.get_our_node_id(),
1029 node_features: NodeFeatures::empty(),
1030 short_channel_id: chan_3.0.contents.short_channel_id,
1031 channel_features: ChannelFeatures::empty(),
1033 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1035 hops.push(RouteHop {
1036 pubkey: nodes[1].node.get_our_node_id(),
1037 node_features: nodes[1].node.node_features(),
1038 short_channel_id: chan_4.0.contents.short_channel_id,
1039 channel_features: nodes[1].node.channel_features(),
1041 cltv_expiry_delta: TEST_FINAL_CLTV,
1043 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;
1044 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;
1045 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;
1047 let mut hops = Vec::with_capacity(3);
1048 hops.push(RouteHop {
1049 pubkey: nodes[3].node.get_our_node_id(),
1050 node_features: NodeFeatures::empty(),
1051 short_channel_id: chan_4.0.contents.short_channel_id,
1052 channel_features: ChannelFeatures::empty(),
1054 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1056 hops.push(RouteHop {
1057 pubkey: nodes[2].node.get_our_node_id(),
1058 node_features: NodeFeatures::empty(),
1059 short_channel_id: chan_3.0.contents.short_channel_id,
1060 channel_features: ChannelFeatures::empty(),
1062 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1064 hops.push(RouteHop {
1065 pubkey: nodes[1].node.get_our_node_id(),
1066 node_features: nodes[1].node.node_features(),
1067 short_channel_id: chan_2.0.contents.short_channel_id,
1068 channel_features: nodes[1].node.channel_features(),
1070 cltv_expiry_delta: TEST_FINAL_CLTV,
1072 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;
1073 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;
1074 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;
1076 // Claim the rebalances...
1077 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1078 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1080 // Close down the channels...
1081 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1082 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1085 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1088 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1089 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1090 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1091 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1092 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1096 fn holding_cell_htlc_counting() {
1097 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1098 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1099 // commitment dance rounds.
1100 let chanmon_cfgs = create_chanmon_cfgs(3);
1101 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1102 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1103 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1104 create_announced_chan_between_nodes(&nodes, 0, 1);
1105 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1107 let mut payments = Vec::new();
1108 for _ in 0..crate::ln::channel::OUR_MAX_HTLCS {
1109 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1110 nodes[1].node.send_payment_with_route(&route, payment_hash,
1111 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1112 payments.push((payment_preimage, payment_hash));
1114 check_added_monitors!(nodes[1], 1);
1116 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1117 assert_eq!(events.len(), 1);
1118 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1119 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1121 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1122 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1124 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1126 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1127 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1128 ), true, APIError::ChannelUnavailable { ref err },
1129 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1130 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1131 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1134 // This should also be true if we try to forward a payment.
1135 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1137 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1138 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1139 check_added_monitors!(nodes[0], 1);
1142 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143 assert_eq!(events.len(), 1);
1144 let payment_event = SendEvent::from_event(events.pop().unwrap());
1145 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150 // fails), the second will process the resulting failure and fail the HTLC backward.
1151 expect_pending_htlcs_forwardable!(nodes[1]);
1152 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 }]);
1153 check_added_monitors!(nodes[1], 1);
1155 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161 // Now forward all the pending HTLCs and claim them back
1162 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164 check_added_monitors!(nodes[2], 1);
1166 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172 check_added_monitors!(nodes[1], 1);
1173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175 for ref update in as_updates.update_add_htlcs.iter() {
1176 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179 check_added_monitors!(nodes[2], 1);
1180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181 check_added_monitors!(nodes[2], 1);
1182 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185 check_added_monitors!(nodes[1], 1);
1186 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187 check_added_monitors!(nodes[1], 1);
1188 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191 check_added_monitors!(nodes[2], 1);
1193 expect_pending_htlcs_forwardable!(nodes[2]);
1195 let events = nodes[2].node.get_and_clear_pending_events();
1196 assert_eq!(events.len(), payments.len());
1197 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199 &Event::PaymentClaimable { ref payment_hash, .. } => {
1200 assert_eq!(*payment_hash, *hash);
1202 _ => panic!("Unexpected event"),
1206 for (preimage, _) in payments.drain(..) {
1207 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1214 fn duplicate_htlc_test() {
1215 // Test that we accept duplicate payment_hash HTLCs across the network and that
1216 // claiming/failing them are all separate and don't affect each other
1217 let chanmon_cfgs = create_chanmon_cfgs(6);
1218 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223 create_announced_chan_between_nodes(&nodes, 0, 3);
1224 create_announced_chan_between_nodes(&nodes, 1, 3);
1225 create_announced_chan_between_nodes(&nodes, 2, 3);
1226 create_announced_chan_between_nodes(&nodes, 3, 4);
1227 create_announced_chan_between_nodes(&nodes, 3, 5);
1229 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234 *nodes[0].network_payment_count.borrow_mut() -= 1;
1235 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244 // Test that ChannelMonitor doesn't generate 2 preimage txn
1245 // when we have 2 HTLCs with same preimage that go across a node
1246 // in opposite directions, even with the same payment secret.
1247 let chanmon_cfgs = create_chanmon_cfgs(2);
1248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1255 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1261 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263 // Provide preimage to node 0 by claiming payment
1264 nodes[0].node.claim_funds(payment_preimage);
1265 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266 check_added_monitors!(nodes[0], 1);
1268 // Broadcast node 1 commitment txn
1269 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272 let mut has_both_htlcs = 0; // check htlcs match ones committed
1273 for outp in remote_txn[0].output.iter() {
1274 if outp.value == 800_000 / 1000 {
1275 has_both_htlcs += 1;
1276 } else if outp.value == 900_000 / 1000 {
1277 has_both_htlcs += 1;
1280 assert_eq!(has_both_htlcs, 2);
1282 mine_transaction(&nodes[0], &remote_txn[0]);
1283 check_added_monitors!(nodes[0], 1);
1284 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1287 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288 assert_eq!(claim_txn.len(), 3);
1290 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1291 check_spends!(claim_txn[1], remote_txn[0]);
1292 check_spends!(claim_txn[2], remote_txn[0]);
1293 let preimage_tx = &claim_txn[0];
1294 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1295 (&claim_txn[1], &claim_txn[2])
1297 (&claim_txn[2], &claim_txn[1])
1300 assert_eq!(preimage_tx.input.len(), 1);
1301 assert_eq!(preimage_bump_tx.input.len(), 1);
1303 assert_eq!(preimage_tx.input.len(), 1);
1304 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1305 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1307 assert_eq!(timeout_tx.input.len(), 1);
1308 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1309 check_spends!(timeout_tx, remote_txn[0]);
1310 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1312 let events = nodes[0].node.get_and_clear_pending_msg_events();
1313 assert_eq!(events.len(), 3);
1316 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1317 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1318 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1319 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1321 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, .. } } => {
1322 assert!(update_add_htlcs.is_empty());
1323 assert!(update_fail_htlcs.is_empty());
1324 assert_eq!(update_fulfill_htlcs.len(), 1);
1325 assert!(update_fail_malformed_htlcs.is_empty());
1326 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1328 _ => panic!("Unexpected event"),
1334 fn test_basic_channel_reserve() {
1335 let chanmon_cfgs = create_chanmon_cfgs(2);
1336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1339 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1341 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1342 let channel_reserve = chan_stat.channel_reserve_msat;
1344 // The 2* and +1 are for the fee spike reserve.
1345 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));
1346 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1347 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1348 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1349 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1351 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1353 &APIError::ChannelUnavailable{ref err} =>
1354 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1355 _ => panic!("Unexpected error variant"),
1358 _ => panic!("Unexpected error variant"),
1360 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1361 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1363 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1367 fn test_fee_spike_violation_fails_htlc() {
1368 let chanmon_cfgs = create_chanmon_cfgs(2);
1369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1371 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1372 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1374 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1375 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1376 let secp_ctx = Secp256k1::new();
1377 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1379 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1381 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1382 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1383 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1384 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1385 let msg = msgs::UpdateAddHTLC {
1388 amount_msat: htlc_msat,
1389 payment_hash: payment_hash,
1390 cltv_expiry: htlc_cltv,
1391 onion_routing_packet: onion_packet,
1394 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1396 // Now manually create the commitment_signed message corresponding to the update_add
1397 // nodes[0] just sent. In the code for construction of this message, "local" refers
1398 // to the sender of the message, and "remote" refers to the receiver.
1400 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1402 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1404 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1405 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1406 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1407 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1408 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1409 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1410 let chan_signer = local_chan.get_signer();
1411 // Make the signer believe we validated another commitment, so we can release the secret
1412 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1414 let pubkeys = chan_signer.pubkeys();
1415 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1416 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1417 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1418 chan_signer.pubkeys().funding_pubkey)
1420 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1421 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1422 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1423 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1424 let chan_signer = remote_chan.get_signer();
1425 let pubkeys = chan_signer.pubkeys();
1426 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1427 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1428 chan_signer.pubkeys().funding_pubkey)
1431 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1432 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1433 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1435 // Build the remote commitment transaction so we can sign it, and then later use the
1436 // signature for the commitment_signed message.
1437 let local_chan_balance = 1313;
1439 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1441 amount_msat: 3460001,
1442 cltv_expiry: htlc_cltv,
1444 transaction_output_index: Some(1),
1447 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1450 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1451 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1452 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1453 let local_chan_signer = local_chan.get_signer();
1454 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1458 local_chan.opt_anchors(), local_funding, remote_funding,
1459 commit_tx_keys.clone(),
1461 &mut vec![(accepted_htlc_info, ())],
1462 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1464 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1467 let commit_signed_msg = msgs::CommitmentSigned {
1470 htlc_signatures: res.1
1473 // Send the commitment_signed message to the nodes[1].
1474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1477 // Send the RAA to nodes[1].
1478 let raa_msg = msgs::RevokeAndACK {
1480 per_commitment_secret: local_secret,
1481 next_per_commitment_point: next_local_point
1483 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1485 let events = nodes[1].node.get_and_clear_pending_msg_events();
1486 assert_eq!(events.len(), 1);
1487 // Make sure the HTLC failed in the way we expect.
1489 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1490 assert_eq!(update_fail_htlcs.len(), 1);
1491 update_fail_htlcs[0].clone()
1493 _ => panic!("Unexpected event"),
1495 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1496 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1498 check_added_monitors!(nodes[1], 2);
1502 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1503 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1504 // Set the fee rate for the channel very high, to the point where the fundee
1505 // sending any above-dust amount would result in a channel reserve violation.
1506 // In this test we check that we would be prevented from sending an HTLC in
1508 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1511 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1512 let default_config = UserConfig::default();
1513 let opt_anchors = false;
1515 let mut push_amt = 100_000_000;
1516 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1518 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1520 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1522 // Sending exactly enough to hit the reserve amount should be accepted
1523 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1524 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1527 // However one more HTLC should be significantly over the reserve amount and fail.
1528 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1529 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1530 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1531 ), true, APIError::ChannelUnavailable { ref err },
1532 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1533 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1534 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);
1538 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1539 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1540 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1543 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1544 let default_config = UserConfig::default();
1545 let opt_anchors = false;
1547 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1548 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1549 // transaction fee with 0 HTLCs (183 sats)).
1550 let mut push_amt = 100_000_000;
1551 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1552 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1553 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1555 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1556 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1557 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1560 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1561 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1562 let secp_ctx = Secp256k1::new();
1563 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1564 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1565 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1566 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1567 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1568 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1569 let msg = msgs::UpdateAddHTLC {
1571 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1572 amount_msat: htlc_msat,
1573 payment_hash: payment_hash,
1574 cltv_expiry: htlc_cltv,
1575 onion_routing_packet: onion_packet,
1578 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1579 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1580 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);
1581 assert_eq!(nodes[0].node.list_channels().len(), 0);
1582 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1583 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1584 check_added_monitors!(nodes[0], 1);
1585 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() });
1589 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1590 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1591 // calculating our commitment transaction fee (this was previously broken).
1592 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1593 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1598 let default_config = UserConfig::default();
1599 let opt_anchors = false;
1601 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1602 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1603 // transaction fee with 0 HTLCs (183 sats)).
1604 let mut push_amt = 100_000_000;
1605 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1606 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1607 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1609 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1610 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1611 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1612 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1613 // commitment transaction fee.
1614 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1616 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1617 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1618 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1621 // One more than the dust amt should fail, however.
1622 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1623 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1624 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1625 ), true, APIError::ChannelUnavailable { ref err },
1626 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1630 fn test_chan_init_feerate_unaffordability() {
1631 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1632 // channel reserve and feerate requirements.
1633 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1637 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1638 let default_config = UserConfig::default();
1639 let opt_anchors = false;
1641 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1643 let mut push_amt = 100_000_000;
1644 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1645 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1646 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1648 // During open, we don't have a "counterparty channel reserve" to check against, so that
1649 // requirement only comes into play on the open_channel handling side.
1650 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1651 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1652 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1653 open_channel_msg.push_msat += 1;
1654 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1656 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1657 assert_eq!(msg_events.len(), 1);
1658 match msg_events[0] {
1659 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1660 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1662 _ => panic!("Unexpected event"),
1667 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1668 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1669 // calculating our counterparty's commitment transaction fee (this was previously broken).
1670 let chanmon_cfgs = create_chanmon_cfgs(2);
1671 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1672 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1673 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1674 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1676 let payment_amt = 46000; // Dust amount
1677 // In the previous code, these first four payments would succeed.
1678 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1679 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1680 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1681 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1691 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1692 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1697 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1698 let chanmon_cfgs = create_chanmon_cfgs(3);
1699 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1700 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1701 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1702 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1703 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1706 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1707 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1708 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1709 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1711 // Add a 2* and +1 for the fee spike reserve.
1712 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1713 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;
1714 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1716 // Add a pending HTLC.
1717 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1718 let payment_event_1 = {
1719 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1720 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1721 check_added_monitors!(nodes[0], 1);
1723 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1724 assert_eq!(events.len(), 1);
1725 SendEvent::from_event(events.remove(0))
1727 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1729 // Attempt to trigger a channel reserve violation --> payment failure.
1730 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1731 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;
1732 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1733 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1735 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1736 let secp_ctx = Secp256k1::new();
1737 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1738 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1739 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1740 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1741 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1742 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1743 let msg = msgs::UpdateAddHTLC {
1746 amount_msat: htlc_msat + 1,
1747 payment_hash: our_payment_hash_1,
1748 cltv_expiry: htlc_cltv,
1749 onion_routing_packet: onion_packet,
1752 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1753 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1754 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1755 assert_eq!(nodes[1].node.list_channels().len(), 1);
1756 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1757 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1758 check_added_monitors!(nodes[1], 1);
1759 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1763 fn test_inbound_outbound_capacity_is_not_zero() {
1764 let chanmon_cfgs = create_chanmon_cfgs(2);
1765 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1766 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1767 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1768 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1769 let channels0 = node_chanmgrs[0].list_channels();
1770 let channels1 = node_chanmgrs[1].list_channels();
1771 let default_config = UserConfig::default();
1772 assert_eq!(channels0.len(), 1);
1773 assert_eq!(channels1.len(), 1);
1775 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1776 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1777 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1779 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1780 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1783 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1784 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1788 fn test_channel_reserve_holding_cell_htlcs() {
1789 let chanmon_cfgs = create_chanmon_cfgs(3);
1790 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1791 // When this test was written, the default base fee floated based on the HTLC count.
1792 // It is now fixed, so we simply set the fee to the expected value here.
1793 let mut config = test_default_channel_config();
1794 config.channel_config.forwarding_fee_base_msat = 239;
1795 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1796 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1797 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1798 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1800 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1801 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1803 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1804 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1806 macro_rules! expect_forward {
1808 let mut events = $node.node.get_and_clear_pending_msg_events();
1809 assert_eq!(events.len(), 1);
1810 check_added_monitors!($node, 1);
1811 let payment_event = SendEvent::from_event(events.remove(0));
1816 let feemsat = 239; // set above
1817 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1818 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1819 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1821 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1823 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1825 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1826 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1827 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);
1828 route.paths[0].last_mut().unwrap().fee_msat += 1;
1829 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1831 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1832 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1833 ), true, APIError::ChannelUnavailable { ref err },
1834 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)));
1835 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1836 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);
1839 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1840 // nodes[0]'s wealth
1842 let amt_msat = recv_value_0 + total_fee_msat;
1843 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1844 // Also, ensure that each payment has enough to be over the dust limit to
1845 // ensure it'll be included in each commit tx fee calculation.
1846 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1847 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1848 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1852 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1853 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1854 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1855 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1856 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1858 let (stat01_, stat11_, stat12_, stat22_) = (
1859 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1860 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1861 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1862 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1865 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1866 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1867 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1868 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1869 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1872 // adding pending output.
1873 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1874 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1875 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1876 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1877 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1878 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1879 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1880 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1881 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1883 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1884 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1885 let amt_msat_1 = recv_value_1 + total_fee_msat;
1887 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);
1888 let payment_event_1 = {
1889 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1890 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1891 check_added_monitors!(nodes[0], 1);
1893 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1894 assert_eq!(events.len(), 1);
1895 SendEvent::from_event(events.remove(0))
1897 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1899 // channel reserve test with htlc pending output > 0
1900 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1902 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1903 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1904 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1905 ), true, APIError::ChannelUnavailable { ref err },
1906 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1907 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1910 // split the rest to test holding cell
1911 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1912 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1913 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1914 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1916 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1917 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);
1920 // now see if they go through on both sides
1921 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);
1922 // but this will stuck in the holding cell
1923 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1924 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1925 check_added_monitors!(nodes[0], 0);
1926 let events = nodes[0].node.get_and_clear_pending_events();
1927 assert_eq!(events.len(), 0);
1929 // test with outbound holding cell amount > 0
1931 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1932 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1933 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1934 ), true, APIError::ChannelUnavailable { ref err },
1935 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1936 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1937 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1940 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);
1941 // this will also stuck in the holding cell
1942 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1943 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1944 check_added_monitors!(nodes[0], 0);
1945 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1946 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1948 // flush the pending htlc
1949 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1950 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1951 check_added_monitors!(nodes[1], 1);
1953 // the pending htlc should be promoted to committed
1954 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1955 check_added_monitors!(nodes[0], 1);
1956 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1958 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1959 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1960 // No commitment_signed so get_event_msg's assert(len == 1) passes
1961 check_added_monitors!(nodes[0], 1);
1963 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1964 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1965 check_added_monitors!(nodes[1], 1);
1967 expect_pending_htlcs_forwardable!(nodes[1]);
1969 let ref payment_event_11 = expect_forward!(nodes[1]);
1970 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1971 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1973 expect_pending_htlcs_forwardable!(nodes[2]);
1974 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1976 // flush the htlcs in the holding cell
1977 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1979 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1980 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1981 expect_pending_htlcs_forwardable!(nodes[1]);
1983 let ref payment_event_3 = expect_forward!(nodes[1]);
1984 assert_eq!(payment_event_3.msgs.len(), 2);
1985 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1986 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1988 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1989 expect_pending_htlcs_forwardable!(nodes[2]);
1991 let events = nodes[2].node.get_and_clear_pending_events();
1992 assert_eq!(events.len(), 2);
1994 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
1995 assert_eq!(our_payment_hash_21, *payment_hash);
1996 assert_eq!(recv_value_21, amount_msat);
1997 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
1998 assert_eq!(via_channel_id, Some(chan_2.2));
2000 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2001 assert!(payment_preimage.is_none());
2002 assert_eq!(our_payment_secret_21, *payment_secret);
2004 _ => panic!("expected PaymentPurpose::InvoicePayment")
2007 _ => panic!("Unexpected event"),
2010 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
2011 assert_eq!(our_payment_hash_22, *payment_hash);
2012 assert_eq!(recv_value_22, amount_msat);
2013 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2014 assert_eq!(via_channel_id, Some(chan_2.2));
2016 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2017 assert!(payment_preimage.is_none());
2018 assert_eq!(our_payment_secret_22, *payment_secret);
2020 _ => panic!("expected PaymentPurpose::InvoicePayment")
2023 _ => panic!("Unexpected event"),
2026 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2027 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2028 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2030 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2031 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2032 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2034 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2035 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);
2036 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2037 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2038 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2040 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2041 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2045 fn channel_reserve_in_flight_removes() {
2046 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2047 // can send to its counterparty, but due to update ordering, the other side may not yet have
2048 // considered those HTLCs fully removed.
2049 // This tests that we don't count HTLCs which will not be included in the next remote
2050 // commitment transaction towards the reserve value (as it implies no commitment transaction
2051 // will be generated which violates the remote reserve value).
2052 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2054 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2055 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2056 // you only consider the value of the first HTLC, it may not),
2057 // * start routing a third HTLC from A to B,
2058 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2059 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2060 // * deliver the first fulfill from B
2061 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2063 // * deliver A's response CS and RAA.
2064 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2065 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2066 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2067 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2068 let chanmon_cfgs = create_chanmon_cfgs(2);
2069 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2070 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2071 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2072 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2074 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2075 // Route the first two HTLCs.
2076 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2077 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2078 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2080 // Start routing the third HTLC (this is just used to get everyone in the right state).
2081 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2083 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2084 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2085 check_added_monitors!(nodes[0], 1);
2086 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2087 assert_eq!(events.len(), 1);
2088 SendEvent::from_event(events.remove(0))
2091 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2092 // initial fulfill/CS.
2093 nodes[1].node.claim_funds(payment_preimage_1);
2094 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2095 check_added_monitors!(nodes[1], 1);
2096 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2098 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2099 // remove the second HTLC when we send the HTLC back from B to A.
2100 nodes[1].node.claim_funds(payment_preimage_2);
2101 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2102 check_added_monitors!(nodes[1], 1);
2103 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2105 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.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_1);
2111 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2112 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2113 check_added_monitors!(nodes[1], 1);
2114 // B is already AwaitingRAA, so cant generate a CS here
2115 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2117 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2118 check_added_monitors!(nodes[1], 1);
2119 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2121 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2122 check_added_monitors!(nodes[0], 1);
2123 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2125 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2126 check_added_monitors!(nodes[1], 1);
2127 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2129 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2130 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2131 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2132 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2133 // on-chain as necessary).
2134 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2135 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2136 check_added_monitors!(nodes[0], 1);
2137 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2138 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2140 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2141 check_added_monitors!(nodes[1], 1);
2142 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2144 expect_pending_htlcs_forwardable!(nodes[1]);
2145 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2147 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2148 // resolve the second HTLC from A's point of view.
2149 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2150 check_added_monitors!(nodes[0], 1);
2151 expect_payment_path_successful!(nodes[0]);
2152 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2154 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2155 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2156 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2158 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2159 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2160 check_added_monitors!(nodes[1], 1);
2161 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2162 assert_eq!(events.len(), 1);
2163 SendEvent::from_event(events.remove(0))
2166 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2167 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2168 check_added_monitors!(nodes[0], 1);
2169 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2171 // Now just resolve all the outstanding messages/HTLCs for completeness...
2173 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2174 check_added_monitors!(nodes[1], 1);
2175 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2177 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2178 check_added_monitors!(nodes[1], 1);
2180 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2181 check_added_monitors!(nodes[0], 1);
2182 expect_payment_path_successful!(nodes[0]);
2183 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2185 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2186 check_added_monitors!(nodes[1], 1);
2187 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2189 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2190 check_added_monitors!(nodes[0], 1);
2192 expect_pending_htlcs_forwardable!(nodes[0]);
2193 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2195 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2196 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2200 fn channel_monitor_network_test() {
2201 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2202 // tests that ChannelMonitor is able to recover from various states.
2203 let chanmon_cfgs = create_chanmon_cfgs(5);
2204 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2205 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2206 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2208 // Create some initial channels
2209 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2210 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2211 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2212 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2214 // Make sure all nodes are at the same starting height
2215 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2216 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2217 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2218 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2219 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2221 // Rebalance the network a bit by relaying one payment through all the channels...
2222 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2223 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2224 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2225 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227 // Simple case with no pending HTLCs:
2228 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2229 check_added_monitors!(nodes[1], 1);
2230 check_closed_broadcast!(nodes[1], true);
2232 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2233 assert_eq!(node_txn.len(), 1);
2234 mine_transaction(&nodes[0], &node_txn[0]);
2235 check_added_monitors!(nodes[0], 1);
2236 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2238 check_closed_broadcast!(nodes[0], true);
2239 assert_eq!(nodes[0].node.list_channels().len(), 0);
2240 assert_eq!(nodes[1].node.list_channels().len(), 1);
2241 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2242 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2244 // One pending HTLC is discarded by the force-close:
2245 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2247 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2248 // broadcasted until we reach the timelock time).
2249 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2250 check_closed_broadcast!(nodes[1], true);
2251 check_added_monitors!(nodes[1], 1);
2253 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2254 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2255 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2256 mine_transaction(&nodes[2], &node_txn[0]);
2257 check_added_monitors!(nodes[2], 1);
2258 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2260 check_closed_broadcast!(nodes[2], true);
2261 assert_eq!(nodes[1].node.list_channels().len(), 0);
2262 assert_eq!(nodes[2].node.list_channels().len(), 1);
2263 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2264 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2266 macro_rules! claim_funds {
2267 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2269 $node.node.claim_funds($preimage);
2270 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2271 check_added_monitors!($node, 1);
2273 let events = $node.node.get_and_clear_pending_msg_events();
2274 assert_eq!(events.len(), 1);
2276 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2277 assert!(update_add_htlcs.is_empty());
2278 assert!(update_fail_htlcs.is_empty());
2279 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2281 _ => panic!("Unexpected event"),
2287 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2288 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2289 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2290 check_added_monitors!(nodes[2], 1);
2291 check_closed_broadcast!(nodes[2], true);
2292 let node2_commitment_txid;
2294 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2295 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2296 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2297 node2_commitment_txid = node_txn[0].txid();
2299 // Claim the payment on nodes[3], giving it knowledge of the preimage
2300 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2301 mine_transaction(&nodes[3], &node_txn[0]);
2302 check_added_monitors!(nodes[3], 1);
2303 check_preimage_claim(&nodes[3], &node_txn);
2305 check_closed_broadcast!(nodes[3], true);
2306 assert_eq!(nodes[2].node.list_channels().len(), 0);
2307 assert_eq!(nodes[3].node.list_channels().len(), 1);
2308 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2309 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2311 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2312 // confusing us in the following tests.
2313 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2315 // One pending HTLC to time out:
2316 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2317 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2320 let (close_chan_update_1, close_chan_update_2) = {
2321 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2322 let events = nodes[3].node.get_and_clear_pending_msg_events();
2323 assert_eq!(events.len(), 2);
2324 let close_chan_update_1 = match events[0] {
2325 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2328 _ => panic!("Unexpected event"),
2331 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2332 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2334 _ => panic!("Unexpected event"),
2336 check_added_monitors!(nodes[3], 1);
2338 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2340 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2341 node_txn.retain(|tx| {
2342 if tx.input[0].previous_output.txid == node2_commitment_txid {
2348 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2350 // Claim the payment on nodes[4], giving it knowledge of the preimage
2351 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2353 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2354 let events = nodes[4].node.get_and_clear_pending_msg_events();
2355 assert_eq!(events.len(), 2);
2356 let close_chan_update_2 = match events[0] {
2357 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2360 _ => panic!("Unexpected event"),
2363 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2364 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2366 _ => panic!("Unexpected event"),
2368 check_added_monitors!(nodes[4], 1);
2369 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2371 mine_transaction(&nodes[4], &node_txn[0]);
2372 check_preimage_claim(&nodes[4], &node_txn);
2373 (close_chan_update_1, close_chan_update_2)
2375 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2376 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2377 assert_eq!(nodes[3].node.list_channels().len(), 0);
2378 assert_eq!(nodes[4].node.list_channels().len(), 0);
2380 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2381 ChannelMonitorUpdateStatus::Completed);
2382 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2383 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2387 fn test_justice_tx() {
2388 // Test justice txn built on revoked HTLC-Success tx, against both sides
2389 let mut alice_config = UserConfig::default();
2390 alice_config.channel_handshake_config.announced_channel = true;
2391 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2392 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2393 let mut bob_config = UserConfig::default();
2394 bob_config.channel_handshake_config.announced_channel = true;
2395 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2396 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2397 let user_cfgs = [Some(alice_config), Some(bob_config)];
2398 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2399 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2400 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2401 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2402 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2403 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2404 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2405 // Create some new channels:
2406 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2408 // A pending HTLC which will be revoked:
2409 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2410 // Get the will-be-revoked local txn from nodes[0]
2411 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2412 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2413 assert_eq!(revoked_local_txn[0].input.len(), 1);
2414 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2415 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2416 assert_eq!(revoked_local_txn[1].input.len(), 1);
2417 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2418 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2419 // Revoke the old state
2420 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2423 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2425 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2426 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2427 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2429 check_spends!(node_txn[0], revoked_local_txn[0]);
2430 node_txn.swap_remove(0);
2432 check_added_monitors!(nodes[1], 1);
2433 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2434 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2436 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2437 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2438 // Verify broadcast of revoked HTLC-timeout
2439 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2440 check_added_monitors!(nodes[0], 1);
2441 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2442 // Broadcast revoked HTLC-timeout on node 1
2443 mine_transaction(&nodes[1], &node_txn[1]);
2444 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2446 get_announce_close_broadcast_events(&nodes, 0, 1);
2448 assert_eq!(nodes[0].node.list_channels().len(), 0);
2449 assert_eq!(nodes[1].node.list_channels().len(), 0);
2451 // We test justice_tx build by A on B's revoked HTLC-Success tx
2452 // Create some new channels:
2453 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2455 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2459 // A pending HTLC which will be revoked:
2460 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2461 // Get the will-be-revoked local txn from B
2462 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2463 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2464 assert_eq!(revoked_local_txn[0].input.len(), 1);
2465 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2466 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2467 // Revoke the old state
2468 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2470 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2472 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2473 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2474 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2476 check_spends!(node_txn[0], revoked_local_txn[0]);
2477 node_txn.swap_remove(0);
2479 check_added_monitors!(nodes[0], 1);
2480 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2482 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2483 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2484 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2485 check_added_monitors!(nodes[1], 1);
2486 mine_transaction(&nodes[0], &node_txn[1]);
2487 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2488 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2490 get_announce_close_broadcast_events(&nodes, 0, 1);
2491 assert_eq!(nodes[0].node.list_channels().len(), 0);
2492 assert_eq!(nodes[1].node.list_channels().len(), 0);
2496 fn revoked_output_claim() {
2497 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2498 // transaction is broadcast by its counterparty
2499 let chanmon_cfgs = create_chanmon_cfgs(2);
2500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2502 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2503 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2504 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2505 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2506 assert_eq!(revoked_local_txn.len(), 1);
2507 // Only output is the full channel value back to nodes[0]:
2508 assert_eq!(revoked_local_txn[0].output.len(), 1);
2509 // Send a payment through, updating everyone's latest commitment txn
2510 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2512 // Inform nodes[1] that nodes[0] broadcast a stale tx
2513 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2514 check_added_monitors!(nodes[1], 1);
2515 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2516 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2517 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2519 check_spends!(node_txn[0], revoked_local_txn[0]);
2521 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2522 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2523 get_announce_close_broadcast_events(&nodes, 0, 1);
2524 check_added_monitors!(nodes[0], 1);
2525 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2529 fn claim_htlc_outputs_shared_tx() {
2530 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2531 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2532 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2535 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2537 // Create some new channel:
2538 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2540 // Rebalance the network to generate htlc in the two directions
2541 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2542 // 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
2543 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2544 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2546 // Get the will-be-revoked local txn from node[0]
2547 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2548 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2549 assert_eq!(revoked_local_txn[0].input.len(), 1);
2550 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2551 assert_eq!(revoked_local_txn[1].input.len(), 1);
2552 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2553 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2554 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2556 //Revoke the old state
2557 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2560 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2561 check_added_monitors!(nodes[0], 1);
2562 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2563 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2564 check_added_monitors!(nodes[1], 1);
2565 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2566 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2567 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2569 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2570 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2572 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2573 check_spends!(node_txn[0], revoked_local_txn[0]);
2575 let mut witness_lens = BTreeSet::new();
2576 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2577 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2578 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2579 assert_eq!(witness_lens.len(), 3);
2580 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2581 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2582 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2584 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2585 // ANTI_REORG_DELAY confirmations.
2586 mine_transaction(&nodes[1], &node_txn[0]);
2587 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2588 expect_payment_failed!(nodes[1], payment_hash_2, false);
2590 get_announce_close_broadcast_events(&nodes, 0, 1);
2591 assert_eq!(nodes[0].node.list_channels().len(), 0);
2592 assert_eq!(nodes[1].node.list_channels().len(), 0);
2596 fn claim_htlc_outputs_single_tx() {
2597 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2598 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2599 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2600 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2602 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2604 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2606 // Rebalance the network to generate htlc in the two directions
2607 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2608 // 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
2609 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2610 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2611 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2613 // Get the will-be-revoked local txn from node[0]
2614 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2616 //Revoke the old state
2617 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2620 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2621 check_added_monitors!(nodes[0], 1);
2622 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2623 check_added_monitors!(nodes[1], 1);
2624 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2625 let mut events = nodes[0].node.get_and_clear_pending_events();
2626 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2627 match events.last().unwrap() {
2628 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2629 _ => panic!("Unexpected event"),
2632 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2633 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2635 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2636 assert_eq!(node_txn.len(), 7);
2638 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2639 assert_eq!(node_txn[0].input.len(), 1);
2640 check_spends!(node_txn[0], chan_1.3);
2641 assert_eq!(node_txn[1].input.len(), 1);
2642 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2643 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2644 check_spends!(node_txn[1], node_txn[0]);
2646 // Justice transactions are indices 2-3-4
2647 assert_eq!(node_txn[2].input.len(), 1);
2648 assert_eq!(node_txn[3].input.len(), 1);
2649 assert_eq!(node_txn[4].input.len(), 1);
2651 check_spends!(node_txn[2], revoked_local_txn[0]);
2652 check_spends!(node_txn[3], revoked_local_txn[0]);
2653 check_spends!(node_txn[4], revoked_local_txn[0]);
2655 let mut witness_lens = BTreeSet::new();
2656 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2657 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2658 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2659 assert_eq!(witness_lens.len(), 3);
2660 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2661 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2662 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2664 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2665 // ANTI_REORG_DELAY confirmations.
2666 mine_transaction(&nodes[1], &node_txn[2]);
2667 mine_transaction(&nodes[1], &node_txn[3]);
2668 mine_transaction(&nodes[1], &node_txn[4]);
2669 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2670 expect_payment_failed!(nodes[1], payment_hash_2, false);
2672 get_announce_close_broadcast_events(&nodes, 0, 1);
2673 assert_eq!(nodes[0].node.list_channels().len(), 0);
2674 assert_eq!(nodes[1].node.list_channels().len(), 0);
2678 fn test_htlc_on_chain_success() {
2679 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2680 // the preimage backward accordingly. So here we test that ChannelManager is
2681 // broadcasting the right event to other nodes in payment path.
2682 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2683 // A --------------------> B ----------------------> C (preimage)
2684 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2685 // commitment transaction was broadcast.
2686 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2688 // B should be able to claim via preimage if A then broadcasts its local tx.
2689 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2690 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2691 // PaymentSent event).
2693 let chanmon_cfgs = create_chanmon_cfgs(3);
2694 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2695 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2696 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2698 // Create some initial channels
2699 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2700 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2702 // Ensure all nodes are at the same height
2703 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2704 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2705 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2706 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2708 // Rebalance the network a bit by relaying one payment through all the channels...
2709 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2710 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2712 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2713 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2715 // Broadcast legit commitment tx from C on B's chain
2716 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2717 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2718 assert_eq!(commitment_tx.len(), 1);
2719 check_spends!(commitment_tx[0], chan_2.3);
2720 nodes[2].node.claim_funds(our_payment_preimage);
2721 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2722 nodes[2].node.claim_funds(our_payment_preimage_2);
2723 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2724 check_added_monitors!(nodes[2], 2);
2725 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2726 assert!(updates.update_add_htlcs.is_empty());
2727 assert!(updates.update_fail_htlcs.is_empty());
2728 assert!(updates.update_fail_malformed_htlcs.is_empty());
2729 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2731 mine_transaction(&nodes[2], &commitment_tx[0]);
2732 check_closed_broadcast!(nodes[2], true);
2733 check_added_monitors!(nodes[2], 1);
2734 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2735 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2736 assert_eq!(node_txn.len(), 2);
2737 check_spends!(node_txn[0], commitment_tx[0]);
2738 check_spends!(node_txn[1], commitment_tx[0]);
2739 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2740 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2741 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2742 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2743 assert_eq!(node_txn[0].lock_time.0, 0);
2744 assert_eq!(node_txn[1].lock_time.0, 0);
2746 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2747 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2748 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2749 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2751 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2752 assert_eq!(added_monitors.len(), 1);
2753 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2754 added_monitors.clear();
2756 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2757 assert_eq!(forwarded_events.len(), 3);
2758 match forwarded_events[0] {
2759 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2760 _ => panic!("Unexpected event"),
2762 let chan_id = Some(chan_1.2);
2763 match forwarded_events[1] {
2764 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2765 assert_eq!(fee_earned_msat, Some(1000));
2766 assert_eq!(prev_channel_id, chan_id);
2767 assert_eq!(claim_from_onchain_tx, true);
2768 assert_eq!(next_channel_id, Some(chan_2.2));
2769 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2773 match forwarded_events[2] {
2774 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2775 assert_eq!(fee_earned_msat, Some(1000));
2776 assert_eq!(prev_channel_id, chan_id);
2777 assert_eq!(claim_from_onchain_tx, true);
2778 assert_eq!(next_channel_id, Some(chan_2.2));
2779 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2783 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2785 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2786 assert_eq!(added_monitors.len(), 2);
2787 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2788 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2789 added_monitors.clear();
2791 assert_eq!(events.len(), 3);
2793 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2794 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2796 match nodes_2_event {
2797 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2798 _ => panic!("Unexpected event"),
2801 match nodes_0_event {
2802 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, .. } } => {
2803 assert!(update_add_htlcs.is_empty());
2804 assert!(update_fail_htlcs.is_empty());
2805 assert_eq!(update_fulfill_htlcs.len(), 1);
2806 assert!(update_fail_malformed_htlcs.is_empty());
2807 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2809 _ => panic!("Unexpected event"),
2812 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2814 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2815 _ => panic!("Unexpected event"),
2818 macro_rules! check_tx_local_broadcast {
2819 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2820 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2821 assert_eq!(node_txn.len(), 2);
2822 // Node[1]: 2 * HTLC-timeout tx
2823 // Node[0]: 2 * HTLC-timeout tx
2824 check_spends!(node_txn[0], $commitment_tx);
2825 check_spends!(node_txn[1], $commitment_tx);
2826 assert_ne!(node_txn[0].lock_time.0, 0);
2827 assert_ne!(node_txn[1].lock_time.0, 0);
2829 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2830 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2831 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2832 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2834 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2835 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2836 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2837 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2842 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2843 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2845 // Broadcast legit commitment tx from A on B's chain
2846 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2847 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2848 check_spends!(node_a_commitment_tx[0], chan_1.3);
2849 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2850 check_closed_broadcast!(nodes[1], true);
2851 check_added_monitors!(nodes[1], 1);
2852 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2853 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2854 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2855 let commitment_spend =
2856 if node_txn.len() == 1 {
2859 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2860 // FullBlockViaListen
2861 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2862 check_spends!(node_txn[1], commitment_tx[0]);
2863 check_spends!(node_txn[2], commitment_tx[0]);
2864 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2867 check_spends!(node_txn[0], commitment_tx[0]);
2868 check_spends!(node_txn[1], commitment_tx[0]);
2869 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2874 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2875 assert_eq!(commitment_spend.input.len(), 2);
2876 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2877 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2878 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2879 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2880 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2881 // we already checked the same situation with A.
2883 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2884 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2885 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2886 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2887 check_closed_broadcast!(nodes[0], true);
2888 check_added_monitors!(nodes[0], 1);
2889 let events = nodes[0].node.get_and_clear_pending_events();
2890 assert_eq!(events.len(), 5);
2891 let mut first_claimed = false;
2892 for event in events {
2894 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2895 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2896 assert!(!first_claimed);
2897 first_claimed = true;
2899 assert_eq!(payment_preimage, our_payment_preimage_2);
2900 assert_eq!(payment_hash, payment_hash_2);
2903 Event::PaymentPathSuccessful { .. } => {},
2904 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2905 _ => panic!("Unexpected event"),
2908 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2911 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2912 // Test that in case of a unilateral close onchain, we detect the state of output and
2913 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2914 // broadcasting the right event to other nodes in payment path.
2915 // A ------------------> B ----------------------> C (timeout)
2916 // B's commitment tx C's commitment tx
2918 // B's HTLC timeout tx B's timeout tx
2920 let chanmon_cfgs = create_chanmon_cfgs(3);
2921 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2922 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2923 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2924 *nodes[0].connect_style.borrow_mut() = connect_style;
2925 *nodes[1].connect_style.borrow_mut() = connect_style;
2926 *nodes[2].connect_style.borrow_mut() = connect_style;
2928 // Create some intial channels
2929 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2930 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2932 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2933 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2934 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2936 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2938 // Broadcast legit commitment tx from C on B's chain
2939 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2940 check_spends!(commitment_tx[0], chan_2.3);
2941 nodes[2].node.fail_htlc_backwards(&payment_hash);
2942 check_added_monitors!(nodes[2], 0);
2943 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2944 check_added_monitors!(nodes[2], 1);
2946 let events = nodes[2].node.get_and_clear_pending_msg_events();
2947 assert_eq!(events.len(), 1);
2949 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, .. } } => {
2950 assert!(update_add_htlcs.is_empty());
2951 assert!(!update_fail_htlcs.is_empty());
2952 assert!(update_fulfill_htlcs.is_empty());
2953 assert!(update_fail_malformed_htlcs.is_empty());
2954 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2956 _ => panic!("Unexpected event"),
2958 mine_transaction(&nodes[2], &commitment_tx[0]);
2959 check_closed_broadcast!(nodes[2], true);
2960 check_added_monitors!(nodes[2], 1);
2961 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2962 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2963 assert_eq!(node_txn.len(), 0);
2965 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2966 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2967 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2968 mine_transaction(&nodes[1], &commitment_tx[0]);
2969 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2972 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2973 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2975 check_spends!(node_txn[2], commitment_tx[0]);
2976 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2978 check_spends!(node_txn[0], chan_2.3);
2979 check_spends!(node_txn[1], node_txn[0]);
2980 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2981 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2983 timeout_tx = node_txn[2].clone();
2987 mine_transaction(&nodes[1], &timeout_tx);
2988 check_added_monitors!(nodes[1], 1);
2989 check_closed_broadcast!(nodes[1], true);
2991 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2993 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 }]);
2994 check_added_monitors!(nodes[1], 1);
2995 let events = nodes[1].node.get_and_clear_pending_msg_events();
2996 assert_eq!(events.len(), 1);
2998 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, .. } } => {
2999 assert!(update_add_htlcs.is_empty());
3000 assert!(!update_fail_htlcs.is_empty());
3001 assert!(update_fulfill_htlcs.is_empty());
3002 assert!(update_fail_malformed_htlcs.is_empty());
3003 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3005 _ => panic!("Unexpected event"),
3008 // Broadcast legit commitment tx from B on A's chain
3009 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3010 check_spends!(commitment_tx[0], chan_1.3);
3012 mine_transaction(&nodes[0], &commitment_tx[0]);
3013 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3015 check_closed_broadcast!(nodes[0], true);
3016 check_added_monitors!(nodes[0], 1);
3017 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3018 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3019 assert_eq!(node_txn.len(), 1);
3020 check_spends!(node_txn[0], commitment_tx[0]);
3021 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3025 fn test_htlc_on_chain_timeout() {
3026 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3027 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3028 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3032 fn test_simple_commitment_revoked_fail_backward() {
3033 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3034 // and fail backward accordingly.
3036 let chanmon_cfgs = create_chanmon_cfgs(3);
3037 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3038 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3039 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3041 // Create some initial channels
3042 create_announced_chan_between_nodes(&nodes, 0, 1);
3043 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3045 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3046 // Get the will-be-revoked local txn from nodes[2]
3047 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3048 // Revoke the old state
3049 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3051 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3053 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3054 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3055 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3056 check_added_monitors!(nodes[1], 1);
3057 check_closed_broadcast!(nodes[1], true);
3059 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 }]);
3060 check_added_monitors!(nodes[1], 1);
3061 let events = nodes[1].node.get_and_clear_pending_msg_events();
3062 assert_eq!(events.len(), 1);
3064 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, .. } } => {
3065 assert!(update_add_htlcs.is_empty());
3066 assert_eq!(update_fail_htlcs.len(), 1);
3067 assert!(update_fulfill_htlcs.is_empty());
3068 assert!(update_fail_malformed_htlcs.is_empty());
3069 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3071 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3072 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3073 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3075 _ => panic!("Unexpected event"),
3079 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3080 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3081 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3082 // commitment transaction anymore.
3083 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3084 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3085 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3086 // technically disallowed and we should probably handle it reasonably.
3087 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3088 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3090 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3091 // commitment_signed (implying it will be in the latest remote commitment transaction).
3092 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3093 // and once they revoke the previous commitment transaction (allowing us to send a new
3094 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3095 let chanmon_cfgs = create_chanmon_cfgs(3);
3096 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3097 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3098 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3100 // Create some initial channels
3101 create_announced_chan_between_nodes(&nodes, 0, 1);
3102 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3104 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 });
3105 // Get the will-be-revoked local txn from nodes[2]
3106 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3107 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3108 // Revoke the old state
3109 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3111 let value = if use_dust {
3112 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3113 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3114 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3115 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3118 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3119 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3120 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3122 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3123 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3124 check_added_monitors!(nodes[2], 1);
3125 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3126 assert!(updates.update_add_htlcs.is_empty());
3127 assert!(updates.update_fulfill_htlcs.is_empty());
3128 assert!(updates.update_fail_malformed_htlcs.is_empty());
3129 assert_eq!(updates.update_fail_htlcs.len(), 1);
3130 assert!(updates.update_fee.is_none());
3131 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3132 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3133 // Drop the last RAA from 3 -> 2
3135 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3136 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3137 check_added_monitors!(nodes[2], 1);
3138 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3139 assert!(updates.update_add_htlcs.is_empty());
3140 assert!(updates.update_fulfill_htlcs.is_empty());
3141 assert!(updates.update_fail_malformed_htlcs.is_empty());
3142 assert_eq!(updates.update_fail_htlcs.len(), 1);
3143 assert!(updates.update_fee.is_none());
3144 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3145 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3146 check_added_monitors!(nodes[1], 1);
3147 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3148 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3149 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3150 check_added_monitors!(nodes[2], 1);
3152 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3153 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3154 check_added_monitors!(nodes[2], 1);
3155 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3156 assert!(updates.update_add_htlcs.is_empty());
3157 assert!(updates.update_fulfill_htlcs.is_empty());
3158 assert!(updates.update_fail_malformed_htlcs.is_empty());
3159 assert_eq!(updates.update_fail_htlcs.len(), 1);
3160 assert!(updates.update_fee.is_none());
3161 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3162 // At this point first_payment_hash has dropped out of the latest two commitment
3163 // transactions that nodes[1] is tracking...
3164 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3165 check_added_monitors!(nodes[1], 1);
3166 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3167 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3168 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3169 check_added_monitors!(nodes[2], 1);
3171 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3172 // on nodes[2]'s RAA.
3173 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3174 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3175 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3176 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3177 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3178 check_added_monitors!(nodes[1], 0);
3181 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3182 // One monitor for the new revocation preimage, no second on as we won't generate a new
3183 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3184 check_added_monitors!(nodes[1], 1);
3185 let events = nodes[1].node.get_and_clear_pending_events();
3186 assert_eq!(events.len(), 2);
3188 Event::PendingHTLCsForwardable { .. } => { },
3189 _ => panic!("Unexpected event"),
3192 Event::HTLCHandlingFailed { .. } => { },
3193 _ => panic!("Unexpected event"),
3195 // Deliberately don't process the pending fail-back so they all fail back at once after
3196 // block connection just like the !deliver_bs_raa case
3199 let mut failed_htlcs = HashSet::new();
3200 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3202 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3203 check_added_monitors!(nodes[1], 1);
3204 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3206 let events = nodes[1].node.get_and_clear_pending_events();
3207 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3209 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3210 _ => panic!("Unexepected event"),
3213 Event::PaymentPathFailed { ref payment_hash, .. } => {
3214 assert_eq!(*payment_hash, fourth_payment_hash);
3216 _ => panic!("Unexpected event"),
3219 Event::PaymentFailed { ref payment_hash, .. } => {
3220 assert_eq!(*payment_hash, fourth_payment_hash);
3222 _ => panic!("Unexpected event"),
3225 nodes[1].node.process_pending_htlc_forwards();
3226 check_added_monitors!(nodes[1], 1);
3228 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3229 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3232 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3233 match nodes_2_event {
3234 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3235 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3236 assert_eq!(update_add_htlcs.len(), 1);
3237 assert!(update_fulfill_htlcs.is_empty());
3238 assert!(update_fail_htlcs.is_empty());
3239 assert!(update_fail_malformed_htlcs.is_empty());
3241 _ => panic!("Unexpected event"),
3245 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3246 match nodes_2_event {
3247 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3248 assert_eq!(channel_id, chan_2.2);
3249 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3251 _ => panic!("Unexpected event"),
3254 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3255 match nodes_0_event {
3256 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, .. } } => {
3257 assert!(update_add_htlcs.is_empty());
3258 assert_eq!(update_fail_htlcs.len(), 3);
3259 assert!(update_fulfill_htlcs.is_empty());
3260 assert!(update_fail_malformed_htlcs.is_empty());
3261 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3263 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3264 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3265 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3267 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3269 let events = nodes[0].node.get_and_clear_pending_events();
3270 assert_eq!(events.len(), 6);
3272 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3273 assert!(failed_htlcs.insert(payment_hash.0));
3274 // If we delivered B's RAA we got an unknown preimage error, not something
3275 // that we should update our routing table for.
3276 if !deliver_bs_raa {
3277 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3280 _ => panic!("Unexpected event"),
3283 Event::PaymentFailed { ref payment_hash, .. } => {
3284 assert_eq!(*payment_hash, first_payment_hash);
3286 _ => panic!("Unexpected event"),
3289 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3290 assert!(failed_htlcs.insert(payment_hash.0));
3292 _ => panic!("Unexpected event"),
3295 Event::PaymentFailed { ref payment_hash, .. } => {
3296 assert_eq!(*payment_hash, second_payment_hash);
3298 _ => panic!("Unexpected event"),
3301 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3302 assert!(failed_htlcs.insert(payment_hash.0));
3304 _ => panic!("Unexpected event"),
3307 Event::PaymentFailed { ref payment_hash, .. } => {
3308 assert_eq!(*payment_hash, third_payment_hash);
3310 _ => panic!("Unexpected event"),
3313 _ => panic!("Unexpected event"),
3316 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3318 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3319 _ => panic!("Unexpected event"),
3322 assert!(failed_htlcs.contains(&first_payment_hash.0));
3323 assert!(failed_htlcs.contains(&second_payment_hash.0));
3324 assert!(failed_htlcs.contains(&third_payment_hash.0));
3328 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3329 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3330 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3331 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3332 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3336 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3337 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3338 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3339 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3340 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3344 fn fail_backward_pending_htlc_upon_channel_failure() {
3345 let chanmon_cfgs = create_chanmon_cfgs(2);
3346 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3347 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3348 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3349 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3351 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3353 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3354 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3355 PaymentId(payment_hash.0)).unwrap();
3356 check_added_monitors!(nodes[0], 1);
3358 let payment_event = {
3359 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3360 assert_eq!(events.len(), 1);
3361 SendEvent::from_event(events.remove(0))
3363 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3364 assert_eq!(payment_event.msgs.len(), 1);
3367 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3368 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3370 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3371 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3372 check_added_monitors!(nodes[0], 0);
3374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3377 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3379 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3381 let secp_ctx = Secp256k1::new();
3382 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3383 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3384 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3385 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3386 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3387 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3389 // Send a 0-msat update_add_htlc to fail the channel.
3390 let update_add_htlc = msgs::UpdateAddHTLC {
3396 onion_routing_packet,
3398 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3400 let events = nodes[0].node.get_and_clear_pending_events();
3401 assert_eq!(events.len(), 3);
3402 // Check that Alice fails backward the pending HTLC from the second payment.
3404 Event::PaymentPathFailed { payment_hash, .. } => {
3405 assert_eq!(payment_hash, failed_payment_hash);
3407 _ => panic!("Unexpected event"),
3410 Event::PaymentFailed { payment_hash, .. } => {
3411 assert_eq!(payment_hash, failed_payment_hash);
3413 _ => panic!("Unexpected event"),
3416 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3417 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3419 _ => panic!("Unexpected event {:?}", events[1]),
3421 check_closed_broadcast!(nodes[0], true);
3422 check_added_monitors!(nodes[0], 1);
3426 fn test_htlc_ignore_latest_remote_commitment() {
3427 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3428 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3429 let chanmon_cfgs = create_chanmon_cfgs(2);
3430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3433 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3434 // We rely on the ability to connect a block redundantly, which isn't allowed via
3435 // `chain::Listen`, so we never run the test if we randomly get assigned that
3439 create_announced_chan_between_nodes(&nodes, 0, 1);
3441 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3442 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3443 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3444 check_closed_broadcast!(nodes[0], true);
3445 check_added_monitors!(nodes[0], 1);
3446 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3448 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3449 assert_eq!(node_txn.len(), 3);
3450 assert_eq!(node_txn[0], node_txn[1]);
3452 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3453 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3454 check_closed_broadcast!(nodes[1], true);
3455 check_added_monitors!(nodes[1], 1);
3456 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3458 // Duplicate the connect_block call since this may happen due to other listeners
3459 // registering new transactions
3460 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3464 fn test_force_close_fail_back() {
3465 // Check which HTLCs are failed-backwards on channel force-closure
3466 let chanmon_cfgs = create_chanmon_cfgs(3);
3467 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3468 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3469 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3470 create_announced_chan_between_nodes(&nodes, 0, 1);
3471 create_announced_chan_between_nodes(&nodes, 1, 2);
3473 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3475 let mut payment_event = {
3476 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3477 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3478 check_added_monitors!(nodes[0], 1);
3480 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3481 assert_eq!(events.len(), 1);
3482 SendEvent::from_event(events.remove(0))
3485 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3486 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3488 expect_pending_htlcs_forwardable!(nodes[1]);
3490 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3491 assert_eq!(events_2.len(), 1);
3492 payment_event = SendEvent::from_event(events_2.remove(0));
3493 assert_eq!(payment_event.msgs.len(), 1);
3495 check_added_monitors!(nodes[1], 1);
3496 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3497 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3498 check_added_monitors!(nodes[2], 1);
3499 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3501 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3502 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3503 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3505 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3506 check_closed_broadcast!(nodes[2], true);
3507 check_added_monitors!(nodes[2], 1);
3508 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3510 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3511 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3512 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3513 // back to nodes[1] upon timeout otherwise.
3514 assert_eq!(node_txn.len(), 1);
3518 mine_transaction(&nodes[1], &tx);
3520 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3521 check_closed_broadcast!(nodes[1], true);
3522 check_added_monitors!(nodes[1], 1);
3523 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3525 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3527 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3528 .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);
3530 mine_transaction(&nodes[2], &tx);
3531 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3532 assert_eq!(node_txn.len(), 1);
3533 assert_eq!(node_txn[0].input.len(), 1);
3534 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3535 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3536 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3538 check_spends!(node_txn[0], tx);
3542 fn test_dup_events_on_peer_disconnect() {
3543 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3544 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3545 // as we used to generate the event immediately upon receipt of the payment preimage in the
3546 // update_fulfill_htlc message.
3548 let chanmon_cfgs = create_chanmon_cfgs(2);
3549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3551 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3552 create_announced_chan_between_nodes(&nodes, 0, 1);
3554 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3556 nodes[1].node.claim_funds(payment_preimage);
3557 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3558 check_added_monitors!(nodes[1], 1);
3559 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3560 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3561 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3563 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3564 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3566 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3567 expect_payment_path_successful!(nodes[0]);
3571 fn test_peer_disconnected_before_funding_broadcasted() {
3572 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3573 // before the funding transaction has been broadcasted.
3574 let chanmon_cfgs = create_chanmon_cfgs(2);
3575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3579 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3580 // broadcasted, even though it's created by `nodes[0]`.
3581 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();
3582 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3583 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3584 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3585 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3587 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3588 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3590 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3592 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3593 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3595 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3596 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3599 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3602 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3603 // disconnected before the funding transaction was broadcasted.
3604 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3605 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3607 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3608 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3612 fn test_simple_peer_disconnect() {
3613 // Test that we can reconnect when there are no lost messages
3614 let chanmon_cfgs = create_chanmon_cfgs(3);
3615 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3616 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3617 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3618 create_announced_chan_between_nodes(&nodes, 0, 1);
3619 create_announced_chan_between_nodes(&nodes, 1, 2);
3621 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3622 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3623 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3625 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3626 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3627 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3628 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3630 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3631 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3632 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3635 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3636 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3637 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3639 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3640 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3642 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3643 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3645 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3647 let events = nodes[0].node.get_and_clear_pending_events();
3648 assert_eq!(events.len(), 4);
3650 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3651 assert_eq!(payment_preimage, payment_preimage_3);
3652 assert_eq!(payment_hash, payment_hash_3);
3654 _ => panic!("Unexpected event"),
3657 Event::PaymentPathSuccessful { .. } => {},
3658 _ => panic!("Unexpected event"),
3661 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3662 assert_eq!(payment_hash, payment_hash_5);
3663 assert!(payment_failed_permanently);
3665 _ => panic!("Unexpected event"),
3668 Event::PaymentFailed { payment_hash, .. } => {
3669 assert_eq!(payment_hash, payment_hash_5);
3671 _ => panic!("Unexpected event"),
3675 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3676 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3679 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3680 // Test that we can reconnect when in-flight HTLC updates get dropped
3681 let chanmon_cfgs = create_chanmon_cfgs(2);
3682 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3683 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3684 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3686 let mut as_channel_ready = None;
3687 let channel_id = if messages_delivered == 0 {
3688 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3689 as_channel_ready = Some(channel_ready);
3690 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3691 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3692 // it before the channel_reestablish message.
3695 create_announced_chan_between_nodes(&nodes, 0, 1).2
3698 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3700 let payment_event = {
3701 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3702 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3703 check_added_monitors!(nodes[0], 1);
3705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3706 assert_eq!(events.len(), 1);
3707 SendEvent::from_event(events.remove(0))
3709 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3711 if messages_delivered < 2 {
3712 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3714 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3715 if messages_delivered >= 3 {
3716 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3717 check_added_monitors!(nodes[1], 1);
3718 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3720 if messages_delivered >= 4 {
3721 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3722 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3723 check_added_monitors!(nodes[0], 1);
3725 if messages_delivered >= 5 {
3726 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3727 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3728 // No commitment_signed so get_event_msg's assert(len == 1) passes
3729 check_added_monitors!(nodes[0], 1);
3731 if messages_delivered >= 6 {
3732 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3733 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3734 check_added_monitors!(nodes[1], 1);
3741 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3742 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3743 if messages_delivered < 3 {
3744 if simulate_broken_lnd {
3745 // lnd has a long-standing bug where they send a channel_ready prior to a
3746 // channel_reestablish if you reconnect prior to channel_ready time.
3748 // Here we simulate that behavior, delivering a channel_ready immediately on
3749 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3750 // in `reconnect_nodes` but we currently don't fail based on that.
3752 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3753 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3755 // Even if the channel_ready messages get exchanged, as long as nothing further was
3756 // received on either side, both sides will need to resend them.
3757 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3758 } else if messages_delivered == 3 {
3759 // nodes[0] still wants its RAA + commitment_signed
3760 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3761 } else if messages_delivered == 4 {
3762 // nodes[0] still wants its commitment_signed
3763 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3764 } else if messages_delivered == 5 {
3765 // nodes[1] still wants its final RAA
3766 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3767 } else if messages_delivered == 6 {
3768 // Everything was delivered...
3769 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3772 let events_1 = nodes[1].node.get_and_clear_pending_events();
3773 if messages_delivered == 0 {
3774 assert_eq!(events_1.len(), 2);
3776 Event::ChannelReady { .. } => { },
3777 _ => panic!("Unexpected event"),
3780 Event::PendingHTLCsForwardable { .. } => { },
3781 _ => panic!("Unexpected event"),
3784 assert_eq!(events_1.len(), 1);
3786 Event::PendingHTLCsForwardable { .. } => { },
3787 _ => panic!("Unexpected event"),
3791 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3792 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3793 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3795 nodes[1].node.process_pending_htlc_forwards();
3797 let events_2 = nodes[1].node.get_and_clear_pending_events();
3798 assert_eq!(events_2.len(), 1);
3800 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, via_user_channel_id: _ } => {
3801 assert_eq!(payment_hash_1, *payment_hash);
3802 assert_eq!(amount_msat, 1_000_000);
3803 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3804 assert_eq!(via_channel_id, Some(channel_id));
3806 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3807 assert!(payment_preimage.is_none());
3808 assert_eq!(payment_secret_1, *payment_secret);
3810 _ => panic!("expected PaymentPurpose::InvoicePayment")
3813 _ => panic!("Unexpected event"),
3816 nodes[1].node.claim_funds(payment_preimage_1);
3817 check_added_monitors!(nodes[1], 1);
3818 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3820 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3821 assert_eq!(events_3.len(), 1);
3822 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3823 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3824 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3825 assert!(updates.update_add_htlcs.is_empty());
3826 assert!(updates.update_fail_htlcs.is_empty());
3827 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3828 assert!(updates.update_fail_malformed_htlcs.is_empty());
3829 assert!(updates.update_fee.is_none());
3830 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3832 _ => panic!("Unexpected event"),
3835 if messages_delivered >= 1 {
3836 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3838 let events_4 = nodes[0].node.get_and_clear_pending_events();
3839 assert_eq!(events_4.len(), 1);
3841 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3842 assert_eq!(payment_preimage_1, *payment_preimage);
3843 assert_eq!(payment_hash_1, *payment_hash);
3845 _ => panic!("Unexpected event"),
3848 if messages_delivered >= 2 {
3849 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3850 check_added_monitors!(nodes[0], 1);
3851 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3853 if messages_delivered >= 3 {
3854 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3855 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3856 check_added_monitors!(nodes[1], 1);
3858 if messages_delivered >= 4 {
3859 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3860 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3861 // No commitment_signed so get_event_msg's assert(len == 1) passes
3862 check_added_monitors!(nodes[1], 1);
3864 if messages_delivered >= 5 {
3865 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3866 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3867 check_added_monitors!(nodes[0], 1);
3874 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3875 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3876 if messages_delivered < 2 {
3877 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3878 if messages_delivered < 1 {
3879 expect_payment_sent!(nodes[0], payment_preimage_1);
3881 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3883 } else if messages_delivered == 2 {
3884 // nodes[0] still wants its RAA + commitment_signed
3885 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3886 } else if messages_delivered == 3 {
3887 // nodes[0] still wants its commitment_signed
3888 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3889 } else if messages_delivered == 4 {
3890 // nodes[1] still wants its final RAA
3891 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3892 } else if messages_delivered == 5 {
3893 // Everything was delivered...
3894 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3897 if messages_delivered == 1 || messages_delivered == 2 {
3898 expect_payment_path_successful!(nodes[0]);
3900 if messages_delivered <= 5 {
3901 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3902 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3904 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3906 if messages_delivered > 2 {
3907 expect_payment_path_successful!(nodes[0]);
3910 // Channel should still work fine...
3911 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3912 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3913 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3917 fn test_drop_messages_peer_disconnect_a() {
3918 do_test_drop_messages_peer_disconnect(0, true);
3919 do_test_drop_messages_peer_disconnect(0, false);
3920 do_test_drop_messages_peer_disconnect(1, false);
3921 do_test_drop_messages_peer_disconnect(2, false);
3925 fn test_drop_messages_peer_disconnect_b() {
3926 do_test_drop_messages_peer_disconnect(3, false);
3927 do_test_drop_messages_peer_disconnect(4, false);
3928 do_test_drop_messages_peer_disconnect(5, false);
3929 do_test_drop_messages_peer_disconnect(6, false);
3933 fn test_channel_ready_without_best_block_updated() {
3934 // Previously, if we were offline when a funding transaction was locked in, and then we came
3935 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3936 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3937 // channel_ready immediately instead.
3938 let chanmon_cfgs = create_chanmon_cfgs(2);
3939 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3940 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3941 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3942 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3944 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3946 let conf_height = nodes[0].best_block_info().1 + 1;
3947 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3948 let block_txn = [funding_tx];
3949 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3950 let conf_block_header = nodes[0].get_block_header(conf_height);
3951 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3953 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3954 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3955 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3959 fn test_drop_messages_peer_disconnect_dual_htlc() {
3960 // Test that we can handle reconnecting when both sides of a channel have pending
3961 // commitment_updates when we disconnect.
3962 let chanmon_cfgs = create_chanmon_cfgs(2);
3963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3965 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3966 create_announced_chan_between_nodes(&nodes, 0, 1);
3968 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3970 // Now try to send a second payment which will fail to send
3971 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3972 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3973 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3974 check_added_monitors!(nodes[0], 1);
3976 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3977 assert_eq!(events_1.len(), 1);
3979 MessageSendEvent::UpdateHTLCs { .. } => {},
3980 _ => panic!("Unexpected event"),
3983 nodes[1].node.claim_funds(payment_preimage_1);
3984 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3985 check_added_monitors!(nodes[1], 1);
3987 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3988 assert_eq!(events_2.len(), 1);
3990 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 } } => {
3991 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3992 assert!(update_add_htlcs.is_empty());
3993 assert_eq!(update_fulfill_htlcs.len(), 1);
3994 assert!(update_fail_htlcs.is_empty());
3995 assert!(update_fail_malformed_htlcs.is_empty());
3996 assert!(update_fee.is_none());
3998 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3999 let events_3 = nodes[0].node.get_and_clear_pending_events();
4000 assert_eq!(events_3.len(), 1);
4002 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4003 assert_eq!(*payment_preimage, payment_preimage_1);
4004 assert_eq!(*payment_hash, payment_hash_1);
4006 _ => panic!("Unexpected event"),
4009 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4010 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4011 // No commitment_signed so get_event_msg's assert(len == 1) passes
4012 check_added_monitors!(nodes[0], 1);
4014 _ => panic!("Unexpected event"),
4017 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4018 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4020 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();
4021 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4022 assert_eq!(reestablish_1.len(), 1);
4023 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();
4024 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4025 assert_eq!(reestablish_2.len(), 1);
4027 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4028 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4029 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4030 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4032 assert!(as_resp.0.is_none());
4033 assert!(bs_resp.0.is_none());
4035 assert!(bs_resp.1.is_none());
4036 assert!(bs_resp.2.is_none());
4038 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4040 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4041 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4042 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4043 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4044 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4045 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4046 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4047 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4048 // No commitment_signed so get_event_msg's assert(len == 1) passes
4049 check_added_monitors!(nodes[1], 1);
4051 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4052 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4053 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4054 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4055 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4056 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4057 assert!(bs_second_commitment_signed.update_fee.is_none());
4058 check_added_monitors!(nodes[1], 1);
4060 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4061 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4062 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4063 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4064 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4065 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4066 assert!(as_commitment_signed.update_fee.is_none());
4067 check_added_monitors!(nodes[0], 1);
4069 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4070 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4071 // No commitment_signed so get_event_msg's assert(len == 1) passes
4072 check_added_monitors!(nodes[0], 1);
4074 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4075 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4076 // No commitment_signed so get_event_msg's assert(len == 1) passes
4077 check_added_monitors!(nodes[1], 1);
4079 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4080 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4081 check_added_monitors!(nodes[1], 1);
4083 expect_pending_htlcs_forwardable!(nodes[1]);
4085 let events_5 = nodes[1].node.get_and_clear_pending_events();
4086 assert_eq!(events_5.len(), 1);
4088 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4089 assert_eq!(payment_hash_2, *payment_hash);
4091 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4092 assert!(payment_preimage.is_none());
4093 assert_eq!(payment_secret_2, *payment_secret);
4095 _ => panic!("expected PaymentPurpose::InvoicePayment")
4098 _ => panic!("Unexpected event"),
4101 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4102 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4103 check_added_monitors!(nodes[0], 1);
4105 expect_payment_path_successful!(nodes[0]);
4106 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4109 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4110 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4111 // to avoid our counterparty failing the channel.
4112 let chanmon_cfgs = create_chanmon_cfgs(2);
4113 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4114 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4115 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4117 create_announced_chan_between_nodes(&nodes, 0, 1);
4119 let our_payment_hash = if send_partial_mpp {
4120 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4121 // Use the utility function send_payment_along_path to send the payment with MPP data which
4122 // indicates there are more HTLCs coming.
4123 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.
4124 let payment_id = PaymentId([42; 32]);
4125 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4126 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4127 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4128 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4129 &None, session_privs[0]).unwrap();
4130 check_added_monitors!(nodes[0], 1);
4131 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4132 assert_eq!(events.len(), 1);
4133 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4134 // hop should *not* yet generate any PaymentClaimable event(s).
4135 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4138 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4141 let mut block = Block {
4142 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4145 connect_block(&nodes[0], &block);
4146 connect_block(&nodes[1], &block);
4147 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4148 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4149 block.header.prev_blockhash = block.block_hash();
4150 connect_block(&nodes[0], &block);
4151 connect_block(&nodes[1], &block);
4154 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4156 check_added_monitors!(nodes[1], 1);
4157 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4158 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4159 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4160 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4161 assert!(htlc_timeout_updates.update_fee.is_none());
4163 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4164 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4165 // 100_000 msat as u64, followed by the height at which we failed back above
4166 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4167 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4168 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4172 fn test_htlc_timeout() {
4173 do_test_htlc_timeout(true);
4174 do_test_htlc_timeout(false);
4177 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4178 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4179 let chanmon_cfgs = create_chanmon_cfgs(3);
4180 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4181 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4182 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4183 create_announced_chan_between_nodes(&nodes, 0, 1);
4184 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4186 // Make sure all nodes are at the same starting height
4187 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4188 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4189 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4191 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4192 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4193 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4194 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4195 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4196 check_added_monitors!(nodes[1], 1);
4198 // Now attempt to route a second payment, which should be placed in the holding cell
4199 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4200 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4201 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4202 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4204 check_added_monitors!(nodes[0], 1);
4205 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4206 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4207 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4208 expect_pending_htlcs_forwardable!(nodes[1]);
4210 check_added_monitors!(nodes[1], 0);
4212 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4213 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4214 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4215 connect_blocks(&nodes[1], 1);
4218 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 }]);
4219 check_added_monitors!(nodes[1], 1);
4220 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4221 assert_eq!(fail_commit.len(), 1);
4222 match fail_commit[0] {
4223 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4224 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4225 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4227 _ => unreachable!(),
4229 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4231 expect_payment_failed!(nodes[1], second_payment_hash, false);
4236 fn test_holding_cell_htlc_add_timeouts() {
4237 do_test_holding_cell_htlc_add_timeouts(false);
4238 do_test_holding_cell_htlc_add_timeouts(true);
4241 macro_rules! check_spendable_outputs {
4242 ($node: expr, $keysinterface: expr) => {
4244 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4245 let mut txn = Vec::new();
4246 let mut all_outputs = Vec::new();
4247 let secp_ctx = Secp256k1::new();
4248 for event in events.drain(..) {
4250 Event::SpendableOutputs { mut outputs } => {
4251 for outp in outputs.drain(..) {
4252 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4253 all_outputs.push(outp);
4256 _ => panic!("Unexpected event"),
4259 if all_outputs.len() > 1 {
4260 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) {
4270 fn test_claim_sizeable_push_msat() {
4271 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4272 let chanmon_cfgs = create_chanmon_cfgs(2);
4273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4275 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4277 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4278 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4279 check_closed_broadcast!(nodes[1], true);
4280 check_added_monitors!(nodes[1], 1);
4281 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4282 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4283 assert_eq!(node_txn.len(), 1);
4284 check_spends!(node_txn[0], chan.3);
4285 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
4287 mine_transaction(&nodes[1], &node_txn[0]);
4288 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4290 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4291 assert_eq!(spend_txn.len(), 1);
4292 assert_eq!(spend_txn[0].input.len(), 1);
4293 check_spends!(spend_txn[0], node_txn[0]);
4294 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4298 fn test_claim_on_remote_sizeable_push_msat() {
4299 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4300 // to_remote output is encumbered by a P2WPKH
4301 let chanmon_cfgs = create_chanmon_cfgs(2);
4302 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4303 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4304 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4306 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4307 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4308 check_closed_broadcast!(nodes[0], true);
4309 check_added_monitors!(nodes[0], 1);
4310 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4312 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4313 assert_eq!(node_txn.len(), 1);
4314 check_spends!(node_txn[0], chan.3);
4315 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
4317 mine_transaction(&nodes[1], &node_txn[0]);
4318 check_closed_broadcast!(nodes[1], true);
4319 check_added_monitors!(nodes[1], 1);
4320 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4321 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4323 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4324 assert_eq!(spend_txn.len(), 1);
4325 check_spends!(spend_txn[0], node_txn[0]);
4329 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4330 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4331 // to_remote output is encumbered by a P2WPKH
4333 let chanmon_cfgs = create_chanmon_cfgs(2);
4334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4336 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4338 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4339 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4340 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4341 assert_eq!(revoked_local_txn[0].input.len(), 1);
4342 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4344 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4345 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4346 check_closed_broadcast!(nodes[1], true);
4347 check_added_monitors!(nodes[1], 1);
4348 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4350 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4351 mine_transaction(&nodes[1], &node_txn[0]);
4352 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4354 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4355 assert_eq!(spend_txn.len(), 3);
4356 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4357 check_spends!(spend_txn[1], node_txn[0]);
4358 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4362 fn test_static_spendable_outputs_preimage_tx() {
4363 let chanmon_cfgs = create_chanmon_cfgs(2);
4364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4366 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4368 // Create some initial channels
4369 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4371 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4373 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4374 assert_eq!(commitment_tx[0].input.len(), 1);
4375 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4377 // Settle A's commitment tx on B's chain
4378 nodes[1].node.claim_funds(payment_preimage);
4379 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4380 check_added_monitors!(nodes[1], 1);
4381 mine_transaction(&nodes[1], &commitment_tx[0]);
4382 check_added_monitors!(nodes[1], 1);
4383 let events = nodes[1].node.get_and_clear_pending_msg_events();
4385 MessageSendEvent::UpdateHTLCs { .. } => {},
4386 _ => panic!("Unexpected event"),
4389 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4390 _ => panic!("Unexepected event"),
4393 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4394 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4395 assert_eq!(node_txn.len(), 1);
4396 check_spends!(node_txn[0], commitment_tx[0]);
4397 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4399 mine_transaction(&nodes[1], &node_txn[0]);
4400 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4401 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4403 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4404 assert_eq!(spend_txn.len(), 1);
4405 check_spends!(spend_txn[0], node_txn[0]);
4409 fn test_static_spendable_outputs_timeout_tx() {
4410 let chanmon_cfgs = create_chanmon_cfgs(2);
4411 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4412 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4413 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4415 // Create some initial channels
4416 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4418 // Rebalance the network a bit by relaying one payment through all the channels ...
4419 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4421 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4423 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4424 assert_eq!(commitment_tx[0].input.len(), 1);
4425 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4427 // Settle A's commitment tx on B' chain
4428 mine_transaction(&nodes[1], &commitment_tx[0]);
4429 check_added_monitors!(nodes[1], 1);
4430 let events = nodes[1].node.get_and_clear_pending_msg_events();
4432 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4433 _ => panic!("Unexpected event"),
4435 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4437 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4438 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4439 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4440 check_spends!(node_txn[0], commitment_tx[0].clone());
4441 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4443 mine_transaction(&nodes[1], &node_txn[0]);
4444 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4445 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4446 expect_payment_failed!(nodes[1], our_payment_hash, false);
4448 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4449 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4450 check_spends!(spend_txn[0], commitment_tx[0]);
4451 check_spends!(spend_txn[1], node_txn[0]);
4452 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4456 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4457 let chanmon_cfgs = create_chanmon_cfgs(2);
4458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4460 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4462 // Create some initial channels
4463 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4465 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4466 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4467 assert_eq!(revoked_local_txn[0].input.len(), 1);
4468 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4470 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4472 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4473 check_closed_broadcast!(nodes[1], true);
4474 check_added_monitors!(nodes[1], 1);
4475 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4477 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4478 assert_eq!(node_txn.len(), 1);
4479 assert_eq!(node_txn[0].input.len(), 2);
4480 check_spends!(node_txn[0], revoked_local_txn[0]);
4482 mine_transaction(&nodes[1], &node_txn[0]);
4483 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4485 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4486 assert_eq!(spend_txn.len(), 1);
4487 check_spends!(spend_txn[0], node_txn[0]);
4491 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4492 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4493 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4494 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4495 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4496 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4498 // Create some initial channels
4499 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4501 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4502 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4503 assert_eq!(revoked_local_txn[0].input.len(), 1);
4504 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4506 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4508 // A will generate HTLC-Timeout from revoked commitment tx
4509 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4510 check_closed_broadcast!(nodes[0], true);
4511 check_added_monitors!(nodes[0], 1);
4512 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4513 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4515 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4516 assert_eq!(revoked_htlc_txn.len(), 1);
4517 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4518 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4519 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4520 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4522 // B will generate justice tx from A's revoked commitment/HTLC tx
4523 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4524 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4525 check_closed_broadcast!(nodes[1], true);
4526 check_added_monitors!(nodes[1], 1);
4527 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4529 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4530 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4531 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4532 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4533 // transactions next...
4534 assert_eq!(node_txn[0].input.len(), 3);
4535 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4537 assert_eq!(node_txn[1].input.len(), 2);
4538 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4539 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4540 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4542 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4543 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4546 mine_transaction(&nodes[1], &node_txn[1]);
4547 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4549 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4550 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4551 assert_eq!(spend_txn.len(), 1);
4552 assert_eq!(spend_txn[0].input.len(), 1);
4553 check_spends!(spend_txn[0], node_txn[1]);
4557 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4558 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4559 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4562 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4564 // Create some initial channels
4565 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4567 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4568 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4569 assert_eq!(revoked_local_txn[0].input.len(), 1);
4570 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4572 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4573 assert_eq!(revoked_local_txn[0].output.len(), 2);
4575 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4577 // B will generate HTLC-Success from revoked commitment tx
4578 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4579 check_closed_broadcast!(nodes[1], true);
4580 check_added_monitors!(nodes[1], 1);
4581 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4582 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4584 assert_eq!(revoked_htlc_txn.len(), 1);
4585 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4586 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4587 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4589 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4590 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4591 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4593 // A will generate justice tx from B's revoked commitment/HTLC tx
4594 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4595 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4596 check_closed_broadcast!(nodes[0], true);
4597 check_added_monitors!(nodes[0], 1);
4598 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4600 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4601 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4603 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4604 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4605 // transactions next...
4606 assert_eq!(node_txn[0].input.len(), 2);
4607 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4608 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4609 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4611 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4612 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4615 assert_eq!(node_txn[1].input.len(), 1);
4616 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4618 mine_transaction(&nodes[0], &node_txn[1]);
4619 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4621 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4622 // didn't try to generate any new transactions.
4624 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4625 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4626 assert_eq!(spend_txn.len(), 3);
4627 assert_eq!(spend_txn[0].input.len(), 1);
4628 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4629 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4630 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4631 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4635 fn test_onchain_to_onchain_claim() {
4636 // Test that in case of channel closure, we detect the state of output and claim HTLC
4637 // on downstream peer's remote commitment tx.
4638 // First, have C claim an HTLC against its own latest commitment transaction.
4639 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4641 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4644 let chanmon_cfgs = create_chanmon_cfgs(3);
4645 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4646 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4647 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4649 // Create some initial channels
4650 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4651 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4653 // Ensure all nodes are at the same height
4654 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4655 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4656 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4657 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4659 // Rebalance the network a bit by relaying one payment through all the channels ...
4660 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4661 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4663 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4664 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4665 check_spends!(commitment_tx[0], chan_2.3);
4666 nodes[2].node.claim_funds(payment_preimage);
4667 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4668 check_added_monitors!(nodes[2], 1);
4669 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4670 assert!(updates.update_add_htlcs.is_empty());
4671 assert!(updates.update_fail_htlcs.is_empty());
4672 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4673 assert!(updates.update_fail_malformed_htlcs.is_empty());
4675 mine_transaction(&nodes[2], &commitment_tx[0]);
4676 check_closed_broadcast!(nodes[2], true);
4677 check_added_monitors!(nodes[2], 1);
4678 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4680 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4681 assert_eq!(c_txn.len(), 1);
4682 check_spends!(c_txn[0], commitment_tx[0]);
4683 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4684 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4685 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4687 // 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
4688 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4689 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4690 check_added_monitors!(nodes[1], 1);
4691 let events = nodes[1].node.get_and_clear_pending_events();
4692 assert_eq!(events.len(), 2);
4694 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4695 _ => panic!("Unexpected event"),
4698 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4699 assert_eq!(fee_earned_msat, Some(1000));
4700 assert_eq!(prev_channel_id, Some(chan_1.2));
4701 assert_eq!(claim_from_onchain_tx, true);
4702 assert_eq!(next_channel_id, Some(chan_2.2));
4703 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4705 _ => panic!("Unexpected event"),
4707 check_added_monitors!(nodes[1], 1);
4708 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4709 assert_eq!(msg_events.len(), 3);
4710 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4711 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4713 match nodes_2_event {
4714 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4715 _ => panic!("Unexpected event"),
4718 match nodes_0_event {
4719 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, .. } } => {
4720 assert!(update_add_htlcs.is_empty());
4721 assert!(update_fail_htlcs.is_empty());
4722 assert_eq!(update_fulfill_htlcs.len(), 1);
4723 assert!(update_fail_malformed_htlcs.is_empty());
4724 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4726 _ => panic!("Unexpected event"),
4729 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4730 match msg_events[0] {
4731 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4732 _ => panic!("Unexpected event"),
4735 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4736 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4737 mine_transaction(&nodes[1], &commitment_tx[0]);
4738 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4739 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4740 // ChannelMonitor: HTLC-Success tx
4741 assert_eq!(b_txn.len(), 1);
4742 check_spends!(b_txn[0], commitment_tx[0]);
4743 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4744 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4745 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4747 check_closed_broadcast!(nodes[1], true);
4748 check_added_monitors!(nodes[1], 1);
4752 fn test_duplicate_payment_hash_one_failure_one_success() {
4753 // Topology : A --> B --> C --> D
4754 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4755 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4756 // we forward one of the payments onwards to D.
4757 let chanmon_cfgs = create_chanmon_cfgs(4);
4758 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4759 // When this test was written, the default base fee floated based on the HTLC count.
4760 // It is now fixed, so we simply set the fee to the expected value here.
4761 let mut config = test_default_channel_config();
4762 config.channel_config.forwarding_fee_base_msat = 196;
4763 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4764 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4765 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4767 create_announced_chan_between_nodes(&nodes, 0, 1);
4768 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4769 create_announced_chan_between_nodes(&nodes, 2, 3);
4771 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4772 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4773 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4774 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4775 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4777 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4779 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4780 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4781 // script push size limit so that the below script length checks match
4782 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4783 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4784 .with_features(nodes[3].node.invoice_features());
4785 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4786 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4788 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4789 assert_eq!(commitment_txn[0].input.len(), 1);
4790 check_spends!(commitment_txn[0], chan_2.3);
4792 mine_transaction(&nodes[1], &commitment_txn[0]);
4793 check_closed_broadcast!(nodes[1], true);
4794 check_added_monitors!(nodes[1], 1);
4795 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4796 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4798 let htlc_timeout_tx;
4799 { // Extract one of the two HTLC-Timeout transaction
4800 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4801 // ChannelMonitor: timeout tx * 2-or-3
4802 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4804 check_spends!(node_txn[0], commitment_txn[0]);
4805 assert_eq!(node_txn[0].input.len(), 1);
4806 assert_eq!(node_txn[0].output.len(), 1);
4808 if node_txn.len() > 2 {
4809 check_spends!(node_txn[1], commitment_txn[0]);
4810 assert_eq!(node_txn[1].input.len(), 1);
4811 assert_eq!(node_txn[1].output.len(), 1);
4812 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4814 check_spends!(node_txn[2], commitment_txn[0]);
4815 assert_eq!(node_txn[2].input.len(), 1);
4816 assert_eq!(node_txn[2].output.len(), 1);
4817 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4819 check_spends!(node_txn[1], commitment_txn[0]);
4820 assert_eq!(node_txn[1].input.len(), 1);
4821 assert_eq!(node_txn[1].output.len(), 1);
4822 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4825 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4826 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4827 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4828 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4829 if node_txn.len() > 2 {
4830 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4831 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4833 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4837 nodes[2].node.claim_funds(our_payment_preimage);
4838 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4840 mine_transaction(&nodes[2], &commitment_txn[0]);
4841 check_added_monitors!(nodes[2], 2);
4842 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4843 let events = nodes[2].node.get_and_clear_pending_msg_events();
4845 MessageSendEvent::UpdateHTLCs { .. } => {},
4846 _ => panic!("Unexpected event"),
4849 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4850 _ => panic!("Unexepected event"),
4852 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4853 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4854 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4855 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4856 assert_eq!(htlc_success_txn[0].input.len(), 1);
4857 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4858 assert_eq!(htlc_success_txn[1].input.len(), 1);
4859 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4860 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4861 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4863 mine_transaction(&nodes[1], &htlc_timeout_tx);
4864 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4865 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 }]);
4866 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4867 assert!(htlc_updates.update_add_htlcs.is_empty());
4868 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4869 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4870 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4871 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4872 check_added_monitors!(nodes[1], 1);
4874 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4877 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4879 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4881 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4882 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4883 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4884 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4885 assert!(updates.update_add_htlcs.is_empty());
4886 assert!(updates.update_fail_htlcs.is_empty());
4887 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4888 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4889 assert!(updates.update_fail_malformed_htlcs.is_empty());
4890 check_added_monitors!(nodes[1], 1);
4892 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4893 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4895 let events = nodes[0].node.get_and_clear_pending_events();
4897 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4898 assert_eq!(*payment_preimage, our_payment_preimage);
4899 assert_eq!(*payment_hash, duplicate_payment_hash);
4901 _ => panic!("Unexpected event"),
4906 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4907 let chanmon_cfgs = create_chanmon_cfgs(2);
4908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4912 // Create some initial channels
4913 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4915 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4916 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4917 assert_eq!(local_txn.len(), 1);
4918 assert_eq!(local_txn[0].input.len(), 1);
4919 check_spends!(local_txn[0], chan_1.3);
4921 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4922 nodes[1].node.claim_funds(payment_preimage);
4923 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4924 check_added_monitors!(nodes[1], 1);
4926 mine_transaction(&nodes[1], &local_txn[0]);
4927 check_added_monitors!(nodes[1], 1);
4928 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4929 let events = nodes[1].node.get_and_clear_pending_msg_events();
4931 MessageSendEvent::UpdateHTLCs { .. } => {},
4932 _ => panic!("Unexpected event"),
4935 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4936 _ => panic!("Unexepected event"),
4939 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4940 assert_eq!(node_txn.len(), 1);
4941 assert_eq!(node_txn[0].input.len(), 1);
4942 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4943 check_spends!(node_txn[0], local_txn[0]);
4947 mine_transaction(&nodes[1], &node_tx);
4948 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4950 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4951 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4952 assert_eq!(spend_txn.len(), 1);
4953 assert_eq!(spend_txn[0].input.len(), 1);
4954 check_spends!(spend_txn[0], node_tx);
4955 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4958 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4959 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4960 // unrevoked commitment transaction.
4961 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4962 // a remote RAA before they could be failed backwards (and combinations thereof).
4963 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4964 // use the same payment hashes.
4965 // Thus, we use a six-node network:
4970 // And test where C fails back to A/B when D announces its latest commitment transaction
4971 let chanmon_cfgs = create_chanmon_cfgs(6);
4972 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4973 // When this test was written, the default base fee floated based on the HTLC count.
4974 // It is now fixed, so we simply set the fee to the expected value here.
4975 let mut config = test_default_channel_config();
4976 config.channel_config.forwarding_fee_base_msat = 196;
4977 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4978 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4979 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4981 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4982 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4983 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4984 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4985 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4987 // Rebalance and check output sanity...
4988 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4989 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4990 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4992 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4993 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4995 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
4997 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
4998 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5000 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
5002 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
5004 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5006 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5007 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5009 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());
5011 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());
5014 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5016 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5017 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
5020 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
5022 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5023 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());
5025 // Double-check that six of the new HTLC were added
5026 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5027 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5028 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5029 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5031 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5032 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5033 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5034 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5035 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5036 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5037 check_added_monitors!(nodes[4], 0);
5039 let failed_destinations = vec![
5040 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5041 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5042 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5043 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5045 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5046 check_added_monitors!(nodes[4], 1);
5048 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5049 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5050 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5051 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5052 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5053 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5055 // Fail 3rd below-dust and 7th above-dust HTLCs
5056 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5057 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5058 check_added_monitors!(nodes[5], 0);
5060 let failed_destinations_2 = vec![
5061 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5062 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5064 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5065 check_added_monitors!(nodes[5], 1);
5067 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5068 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5069 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5070 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5072 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5074 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5075 let failed_destinations_3 = vec![
5076 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5077 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5078 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5079 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5080 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5081 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5083 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5084 check_added_monitors!(nodes[3], 1);
5085 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5086 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5087 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5088 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5089 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5090 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5091 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5092 if deliver_last_raa {
5093 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5095 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5098 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5099 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5100 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5101 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5103 // We now broadcast the latest commitment transaction, which *should* result in failures for
5104 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5105 // the non-broadcast above-dust HTLCs.
5107 // Alternatively, we may broadcast the previous commitment transaction, which should only
5108 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5109 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5111 if announce_latest {
5112 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5114 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5116 let events = nodes[2].node.get_and_clear_pending_events();
5117 let close_event = if deliver_last_raa {
5118 assert_eq!(events.len(), 2 + 6);
5119 events.last().clone().unwrap()
5121 assert_eq!(events.len(), 1);
5122 events.last().clone().unwrap()
5125 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5126 _ => panic!("Unexpected event"),
5129 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5130 check_closed_broadcast!(nodes[2], true);
5131 if deliver_last_raa {
5132 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5134 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();
5135 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5137 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5138 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5140 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5143 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5145 check_added_monitors!(nodes[2], 3);
5147 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5148 assert_eq!(cs_msgs.len(), 2);
5149 let mut a_done = false;
5150 for msg in cs_msgs {
5152 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5153 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5154 // should be failed-backwards here.
5155 let target = if *node_id == nodes[0].node.get_our_node_id() {
5156 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5157 for htlc in &updates.update_fail_htlcs {
5158 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 });
5160 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5165 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5166 for htlc in &updates.update_fail_htlcs {
5167 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5169 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5170 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5174 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5175 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5176 if announce_latest {
5177 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5178 if *node_id == nodes[0].node.get_our_node_id() {
5179 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5182 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5184 _ => panic!("Unexpected event"),
5188 let as_events = nodes[0].node.get_and_clear_pending_events();
5189 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5190 let mut as_failds = HashSet::new();
5191 let mut as_updates = 0;
5192 for event in as_events.iter() {
5193 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5194 assert!(as_failds.insert(*payment_hash));
5195 if *payment_hash != payment_hash_2 {
5196 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5198 assert!(!payment_failed_permanently);
5200 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5203 } else if let &Event::PaymentFailed { .. } = event {
5204 } else { panic!("Unexpected event"); }
5206 assert!(as_failds.contains(&payment_hash_1));
5207 assert!(as_failds.contains(&payment_hash_2));
5208 if announce_latest {
5209 assert!(as_failds.contains(&payment_hash_3));
5210 assert!(as_failds.contains(&payment_hash_5));
5212 assert!(as_failds.contains(&payment_hash_6));
5214 let bs_events = nodes[1].node.get_and_clear_pending_events();
5215 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5216 let mut bs_failds = HashSet::new();
5217 let mut bs_updates = 0;
5218 for event in bs_events.iter() {
5219 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5220 assert!(bs_failds.insert(*payment_hash));
5221 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5222 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5224 assert!(!payment_failed_permanently);
5226 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5229 } else if let &Event::PaymentFailed { .. } = event {
5230 } else { panic!("Unexpected event"); }
5232 assert!(bs_failds.contains(&payment_hash_1));
5233 assert!(bs_failds.contains(&payment_hash_2));
5234 if announce_latest {
5235 assert!(bs_failds.contains(&payment_hash_4));
5237 assert!(bs_failds.contains(&payment_hash_5));
5239 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5240 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5241 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5242 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5243 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5244 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5248 fn test_fail_backwards_latest_remote_announce_a() {
5249 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5253 fn test_fail_backwards_latest_remote_announce_b() {
5254 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5258 fn test_fail_backwards_previous_remote_announce() {
5259 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5260 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5261 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5265 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5266 let chanmon_cfgs = create_chanmon_cfgs(2);
5267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5271 // Create some initial channels
5272 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5274 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5275 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5276 assert_eq!(local_txn[0].input.len(), 1);
5277 check_spends!(local_txn[0], chan_1.3);
5279 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5280 mine_transaction(&nodes[0], &local_txn[0]);
5281 check_closed_broadcast!(nodes[0], true);
5282 check_added_monitors!(nodes[0], 1);
5283 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5284 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5286 let htlc_timeout = {
5287 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5288 assert_eq!(node_txn.len(), 1);
5289 assert_eq!(node_txn[0].input.len(), 1);
5290 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5291 check_spends!(node_txn[0], local_txn[0]);
5295 mine_transaction(&nodes[0], &htlc_timeout);
5296 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5297 expect_payment_failed!(nodes[0], our_payment_hash, false);
5299 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5300 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5301 assert_eq!(spend_txn.len(), 3);
5302 check_spends!(spend_txn[0], local_txn[0]);
5303 assert_eq!(spend_txn[1].input.len(), 1);
5304 check_spends!(spend_txn[1], htlc_timeout);
5305 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5306 assert_eq!(spend_txn[2].input.len(), 2);
5307 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5308 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5309 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5313 fn test_key_derivation_params() {
5314 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5315 // manager rotation to test that `channel_keys_id` returned in
5316 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5317 // then derive a `delayed_payment_key`.
5319 let chanmon_cfgs = create_chanmon_cfgs(3);
5321 // We manually create the node configuration to backup the seed.
5322 let seed = [42; 32];
5323 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5324 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);
5325 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5326 let scorer = Mutex::new(test_utils::TestScorer::new());
5327 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5328 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)) };
5329 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5330 node_cfgs.remove(0);
5331 node_cfgs.insert(0, node);
5333 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5334 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5336 // Create some initial channels
5337 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5339 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5340 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5341 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5343 // Ensure all nodes are at the same height
5344 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5345 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5346 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5347 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5349 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5350 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5351 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5352 assert_eq!(local_txn_1[0].input.len(), 1);
5353 check_spends!(local_txn_1[0], chan_1.3);
5355 // We check funding pubkey are unique
5356 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]));
5357 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]));
5358 if from_0_funding_key_0 == from_1_funding_key_0
5359 || from_0_funding_key_0 == from_1_funding_key_1
5360 || from_0_funding_key_1 == from_1_funding_key_0
5361 || from_0_funding_key_1 == from_1_funding_key_1 {
5362 panic!("Funding pubkeys aren't unique");
5365 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5366 mine_transaction(&nodes[0], &local_txn_1[0]);
5367 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5368 check_closed_broadcast!(nodes[0], true);
5369 check_added_monitors!(nodes[0], 1);
5370 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5372 let htlc_timeout = {
5373 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5374 assert_eq!(node_txn.len(), 1);
5375 assert_eq!(node_txn[0].input.len(), 1);
5376 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5377 check_spends!(node_txn[0], local_txn_1[0]);
5381 mine_transaction(&nodes[0], &htlc_timeout);
5382 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5383 expect_payment_failed!(nodes[0], our_payment_hash, false);
5385 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5386 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5387 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5388 assert_eq!(spend_txn.len(), 3);
5389 check_spends!(spend_txn[0], local_txn_1[0]);
5390 assert_eq!(spend_txn[1].input.len(), 1);
5391 check_spends!(spend_txn[1], htlc_timeout);
5392 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5393 assert_eq!(spend_txn[2].input.len(), 2);
5394 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5395 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5396 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5400 fn test_static_output_closing_tx() {
5401 let chanmon_cfgs = create_chanmon_cfgs(2);
5402 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5403 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5404 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5406 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5408 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5409 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5411 mine_transaction(&nodes[0], &closing_tx);
5412 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5413 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5415 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5416 assert_eq!(spend_txn.len(), 1);
5417 check_spends!(spend_txn[0], closing_tx);
5419 mine_transaction(&nodes[1], &closing_tx);
5420 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5421 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5423 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5424 assert_eq!(spend_txn.len(), 1);
5425 check_spends!(spend_txn[0], closing_tx);
5428 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5429 let chanmon_cfgs = create_chanmon_cfgs(2);
5430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5433 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5435 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5437 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5438 // present in B's local commitment transaction, but none of A's commitment transactions.
5439 nodes[1].node.claim_funds(payment_preimage);
5440 check_added_monitors!(nodes[1], 1);
5441 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5443 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5444 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5445 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5447 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5448 check_added_monitors!(nodes[0], 1);
5449 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5450 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5451 check_added_monitors!(nodes[1], 1);
5453 let starting_block = nodes[1].best_block_info();
5454 let mut block = Block {
5455 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5458 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5459 connect_block(&nodes[1], &block);
5460 block.header.prev_blockhash = block.block_hash();
5462 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5463 check_closed_broadcast!(nodes[1], true);
5464 check_added_monitors!(nodes[1], 1);
5465 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5468 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5469 let chanmon_cfgs = create_chanmon_cfgs(2);
5470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5473 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5475 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5476 nodes[0].node.send_payment_with_route(&route, payment_hash,
5477 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5478 check_added_monitors!(nodes[0], 1);
5480 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5482 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5483 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5484 // to "time out" the HTLC.
5486 let starting_block = nodes[1].best_block_info();
5487 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5489 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5490 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5491 header.prev_blockhash = header.block_hash();
5493 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5494 check_closed_broadcast!(nodes[0], true);
5495 check_added_monitors!(nodes[0], 1);
5496 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5499 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5500 let chanmon_cfgs = create_chanmon_cfgs(3);
5501 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5502 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5503 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5504 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5506 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5507 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5508 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5509 // actually revoked.
5510 let htlc_value = if use_dust { 50000 } else { 3000000 };
5511 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5512 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5513 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5514 check_added_monitors!(nodes[1], 1);
5516 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5517 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5518 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5519 check_added_monitors!(nodes[0], 1);
5520 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5521 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5522 check_added_monitors!(nodes[1], 1);
5523 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5524 check_added_monitors!(nodes[1], 1);
5525 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5527 if check_revoke_no_close {
5528 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5529 check_added_monitors!(nodes[0], 1);
5532 let starting_block = nodes[1].best_block_info();
5533 let mut block = Block {
5534 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5537 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5538 connect_block(&nodes[0], &block);
5539 block.header.prev_blockhash = block.block_hash();
5541 if !check_revoke_no_close {
5542 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5543 check_closed_broadcast!(nodes[0], true);
5544 check_added_monitors!(nodes[0], 1);
5545 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5547 expect_payment_failed!(nodes[0], our_payment_hash, true);
5551 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5552 // There are only a few cases to test here:
5553 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5554 // broadcastable commitment transactions result in channel closure,
5555 // * its included in an unrevoked-but-previous remote commitment transaction,
5556 // * its included in the latest remote or local commitment transactions.
5557 // We test each of the three possible commitment transactions individually and use both dust and
5559 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5560 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5561 // tested for at least one of the cases in other tests.
5563 fn htlc_claim_single_commitment_only_a() {
5564 do_htlc_claim_local_commitment_only(true);
5565 do_htlc_claim_local_commitment_only(false);
5567 do_htlc_claim_current_remote_commitment_only(true);
5568 do_htlc_claim_current_remote_commitment_only(false);
5572 fn htlc_claim_single_commitment_only_b() {
5573 do_htlc_claim_previous_remote_commitment_only(true, false);
5574 do_htlc_claim_previous_remote_commitment_only(false, false);
5575 do_htlc_claim_previous_remote_commitment_only(true, true);
5576 do_htlc_claim_previous_remote_commitment_only(false, true);
5581 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5582 let chanmon_cfgs = create_chanmon_cfgs(2);
5583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5585 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5586 // Force duplicate randomness for every get-random call
5587 for node in nodes.iter() {
5588 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5591 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5592 let channel_value_satoshis=10000;
5593 let push_msat=10001;
5594 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5595 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5596 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5597 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5599 // Create a second channel with the same random values. This used to panic due to a colliding
5600 // channel_id, but now panics due to a colliding outbound SCID alias.
5601 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5605 fn bolt2_open_channel_sending_node_checks_part2() {
5606 let chanmon_cfgs = create_chanmon_cfgs(2);
5607 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5608 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5609 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5611 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5612 let channel_value_satoshis=2^24;
5613 let push_msat=10001;
5614 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5616 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5617 let channel_value_satoshis=10000;
5618 // Test when push_msat is equal to 1000 * funding_satoshis.
5619 let push_msat=1000*channel_value_satoshis+1;
5620 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5622 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5623 let channel_value_satoshis=10000;
5624 let push_msat=10001;
5625 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
5626 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5627 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5629 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5630 // 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
5631 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5633 // 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.
5634 assert!(BREAKDOWN_TIMEOUT>0);
5635 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5637 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5638 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5639 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5641 // 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.
5642 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5643 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5644 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5645 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5646 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5650 fn bolt2_open_channel_sane_dust_limit() {
5651 let chanmon_cfgs = create_chanmon_cfgs(2);
5652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5654 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5656 let channel_value_satoshis=1000000;
5657 let push_msat=10001;
5658 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5659 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5660 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5661 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5663 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5664 let events = nodes[1].node.get_and_clear_pending_msg_events();
5665 let err_msg = match events[0] {
5666 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5669 _ => panic!("Unexpected event"),
5671 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5674 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5675 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5676 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5677 // is no longer affordable once it's freed.
5679 fn test_fail_holding_cell_htlc_upon_free() {
5680 let chanmon_cfgs = create_chanmon_cfgs(2);
5681 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5682 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5683 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5684 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5686 // First nodes[0] generates an update_fee, setting the channel's
5687 // pending_update_fee.
5689 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5690 *feerate_lock += 20;
5692 nodes[0].node.timer_tick_occurred();
5693 check_added_monitors!(nodes[0], 1);
5695 let events = nodes[0].node.get_and_clear_pending_msg_events();
5696 assert_eq!(events.len(), 1);
5697 let (update_msg, commitment_signed) = match events[0] {
5698 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5699 (update_fee.as_ref(), commitment_signed)
5701 _ => panic!("Unexpected event"),
5704 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5706 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5707 let channel_reserve = chan_stat.channel_reserve_msat;
5708 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5709 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5711 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5712 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5713 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5715 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5716 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5717 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5718 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5719 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5721 // Flush the pending fee update.
5722 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5723 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5724 check_added_monitors!(nodes[1], 1);
5725 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5726 check_added_monitors!(nodes[0], 1);
5728 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5729 // HTLC, but now that the fee has been raised the payment will now fail, causing
5730 // us to surface its failure to the user.
5731 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5732 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5733 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);
5734 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 {}",
5735 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5736 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5738 // Check that the payment failed to be sent out.
5739 let events = nodes[0].node.get_and_clear_pending_events();
5740 assert_eq!(events.len(), 2);
5742 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5743 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5744 assert_eq!(our_payment_hash.clone(), *payment_hash);
5745 assert_eq!(*payment_failed_permanently, false);
5746 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5748 _ => panic!("Unexpected event"),
5751 &Event::PaymentFailed { ref payment_hash, .. } => {
5752 assert_eq!(our_payment_hash.clone(), *payment_hash);
5754 _ => panic!("Unexpected event"),
5758 // Test that if multiple HTLCs are released from the holding cell and one is
5759 // valid but the other is no longer valid upon release, the valid HTLC can be
5760 // successfully completed while the other one fails as expected.
5762 fn test_free_and_fail_holding_cell_htlcs() {
5763 let chanmon_cfgs = create_chanmon_cfgs(2);
5764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5767 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5769 // First nodes[0] generates an update_fee, setting the channel's
5770 // pending_update_fee.
5772 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5773 *feerate_lock += 200;
5775 nodes[0].node.timer_tick_occurred();
5776 check_added_monitors!(nodes[0], 1);
5778 let events = nodes[0].node.get_and_clear_pending_msg_events();
5779 assert_eq!(events.len(), 1);
5780 let (update_msg, commitment_signed) = match events[0] {
5781 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5782 (update_fee.as_ref(), commitment_signed)
5784 _ => panic!("Unexpected event"),
5787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5789 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5790 let channel_reserve = chan_stat.channel_reserve_msat;
5791 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5792 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5794 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5796 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5797 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5798 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5800 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5801 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5802 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5803 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5804 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5805 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5806 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5807 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5808 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5809 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5811 // Flush the pending fee update.
5812 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5813 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5814 check_added_monitors!(nodes[1], 1);
5815 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5816 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5817 check_added_monitors!(nodes[0], 2);
5819 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5820 // but now that the fee has been raised the second payment will now fail, causing us
5821 // to surface its failure to the user. The first payment should succeed.
5822 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5823 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5824 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);
5825 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 {}",
5826 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5827 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5829 // Check that the second payment failed to be sent out.
5830 let events = nodes[0].node.get_and_clear_pending_events();
5831 assert_eq!(events.len(), 2);
5833 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5834 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5835 assert_eq!(payment_hash_2.clone(), *payment_hash);
5836 assert_eq!(*payment_failed_permanently, false);
5837 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5839 _ => panic!("Unexpected event"),
5842 &Event::PaymentFailed { ref payment_hash, .. } => {
5843 assert_eq!(payment_hash_2.clone(), *payment_hash);
5845 _ => panic!("Unexpected event"),
5848 // Complete the first payment and the RAA from the fee update.
5849 let (payment_event, send_raa_event) = {
5850 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5851 assert_eq!(msgs.len(), 2);
5852 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5854 let raa = match send_raa_event {
5855 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5856 _ => panic!("Unexpected event"),
5858 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5859 check_added_monitors!(nodes[1], 1);
5860 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5861 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5862 let events = nodes[1].node.get_and_clear_pending_events();
5863 assert_eq!(events.len(), 1);
5865 Event::PendingHTLCsForwardable { .. } => {},
5866 _ => panic!("Unexpected event"),
5868 nodes[1].node.process_pending_htlc_forwards();
5869 let events = nodes[1].node.get_and_clear_pending_events();
5870 assert_eq!(events.len(), 1);
5872 Event::PaymentClaimable { .. } => {},
5873 _ => panic!("Unexpected event"),
5875 nodes[1].node.claim_funds(payment_preimage_1);
5876 check_added_monitors!(nodes[1], 1);
5877 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5879 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5880 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5881 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5882 expect_payment_sent!(nodes[0], payment_preimage_1);
5885 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5886 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5887 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5890 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5891 let chanmon_cfgs = create_chanmon_cfgs(3);
5892 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5893 // When this test was written, the default base fee floated based on the HTLC count.
5894 // It is now fixed, so we simply set the fee to the expected value here.
5895 let mut config = test_default_channel_config();
5896 config.channel_config.forwarding_fee_base_msat = 196;
5897 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5898 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5899 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5900 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5902 // First nodes[1] generates an update_fee, setting the channel's
5903 // pending_update_fee.
5905 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5906 *feerate_lock += 20;
5908 nodes[1].node.timer_tick_occurred();
5909 check_added_monitors!(nodes[1], 1);
5911 let events = nodes[1].node.get_and_clear_pending_msg_events();
5912 assert_eq!(events.len(), 1);
5913 let (update_msg, commitment_signed) = match events[0] {
5914 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5915 (update_fee.as_ref(), commitment_signed)
5917 _ => panic!("Unexpected event"),
5920 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5922 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5923 let channel_reserve = chan_stat.channel_reserve_msat;
5924 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5925 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5927 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5929 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5930 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5931 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5932 let payment_event = {
5933 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5934 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5935 check_added_monitors!(nodes[0], 1);
5937 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5938 assert_eq!(events.len(), 1);
5940 SendEvent::from_event(events.remove(0))
5942 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5943 check_added_monitors!(nodes[1], 0);
5944 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5945 expect_pending_htlcs_forwardable!(nodes[1]);
5947 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5948 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5950 // Flush the pending fee update.
5951 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5952 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5953 check_added_monitors!(nodes[2], 1);
5954 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5955 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5956 check_added_monitors!(nodes[1], 2);
5958 // A final RAA message is generated to finalize the fee update.
5959 let events = nodes[1].node.get_and_clear_pending_msg_events();
5960 assert_eq!(events.len(), 1);
5962 let raa_msg = match &events[0] {
5963 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5966 _ => panic!("Unexpected event"),
5969 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5970 check_added_monitors!(nodes[2], 1);
5971 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5973 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5974 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5975 assert_eq!(process_htlc_forwards_event.len(), 2);
5976 match &process_htlc_forwards_event[0] {
5977 &Event::PendingHTLCsForwardable { .. } => {},
5978 _ => panic!("Unexpected event"),
5981 // In response, we call ChannelManager's process_pending_htlc_forwards
5982 nodes[1].node.process_pending_htlc_forwards();
5983 check_added_monitors!(nodes[1], 1);
5985 // This causes the HTLC to be failed backwards.
5986 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5987 assert_eq!(fail_event.len(), 1);
5988 let (fail_msg, commitment_signed) = match &fail_event[0] {
5989 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5990 assert_eq!(updates.update_add_htlcs.len(), 0);
5991 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5992 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5993 assert_eq!(updates.update_fail_htlcs.len(), 1);
5994 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5996 _ => panic!("Unexpected event"),
5999 // Pass the failure messages back to nodes[0].
6000 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6001 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6003 // Complete the HTLC failure+removal process.
6004 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6005 check_added_monitors!(nodes[0], 1);
6006 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6007 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6008 check_added_monitors!(nodes[1], 2);
6009 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6010 assert_eq!(final_raa_event.len(), 1);
6011 let raa = match &final_raa_event[0] {
6012 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6013 _ => panic!("Unexpected event"),
6015 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6016 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6017 check_added_monitors!(nodes[0], 1);
6020 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6021 // 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.
6022 //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.
6025 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6026 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6027 let chanmon_cfgs = create_chanmon_cfgs(2);
6028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6030 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6031 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6033 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6034 route.paths[0][0].fee_msat = 100;
6036 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6037 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6038 ), true, APIError::ChannelUnavailable { ref err },
6039 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6041 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6045 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6046 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6047 let chanmon_cfgs = create_chanmon_cfgs(2);
6048 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6049 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6050 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6051 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6053 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6054 route.paths[0][0].fee_msat = 0;
6055 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6056 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6057 true, APIError::ChannelUnavailable { ref err },
6058 assert_eq!(err, "Cannot send 0-msat HTLC"));
6060 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6061 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6065 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6066 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6067 let chanmon_cfgs = create_chanmon_cfgs(2);
6068 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6069 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6070 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6071 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6073 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6074 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6075 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6076 check_added_monitors!(nodes[0], 1);
6077 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6078 updates.update_add_htlcs[0].amount_msat = 0;
6080 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6081 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6082 check_closed_broadcast!(nodes[1], true).unwrap();
6083 check_added_monitors!(nodes[1], 1);
6084 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6088 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6089 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6090 //It is enforced when constructing a route.
6091 let chanmon_cfgs = create_chanmon_cfgs(2);
6092 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6093 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6094 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6095 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6097 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6098 .with_features(nodes[1].node.invoice_features());
6099 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6100 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6101 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6102 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6103 ), true, APIError::InvalidRoute { ref err },
6104 assert_eq!(err, &"Channel CLTV overflowed?"));
6108 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6109 //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.
6110 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6111 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6112 let chanmon_cfgs = create_chanmon_cfgs(2);
6113 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6114 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6115 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6116 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6117 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6118 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6120 for i in 0..max_accepted_htlcs {
6121 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6122 let payment_event = {
6123 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6124 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6125 check_added_monitors!(nodes[0], 1);
6127 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6128 assert_eq!(events.len(), 1);
6129 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6130 assert_eq!(htlcs[0].htlc_id, i);
6134 SendEvent::from_event(events.remove(0))
6136 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6137 check_added_monitors!(nodes[1], 0);
6138 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6140 expect_pending_htlcs_forwardable!(nodes[1]);
6141 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6143 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6144 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6145 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6146 ), true, APIError::ChannelUnavailable { ref err },
6147 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6149 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6150 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6154 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6155 //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.
6156 let chanmon_cfgs = create_chanmon_cfgs(2);
6157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6159 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6160 let channel_value = 100000;
6161 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6162 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6164 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6166 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6167 // Manually create a route over our max in flight (which our router normally automatically
6169 route.paths[0][0].fee_msat = max_in_flight + 1;
6170 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6171 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6172 ), true, APIError::ChannelUnavailable { ref err },
6173 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)));
6175 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6176 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);
6178 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6181 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6183 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6184 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6185 let chanmon_cfgs = create_chanmon_cfgs(2);
6186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6187 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6188 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6189 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6190 let htlc_minimum_msat: u64;
6192 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6193 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6194 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6195 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6198 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6199 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6200 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6201 check_added_monitors!(nodes[0], 1);
6202 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6203 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6204 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6205 assert!(nodes[1].node.list_channels().is_empty());
6206 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6207 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()));
6208 check_added_monitors!(nodes[1], 1);
6209 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6213 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6214 //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
6215 let chanmon_cfgs = create_chanmon_cfgs(2);
6216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6218 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6219 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6221 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6222 let channel_reserve = chan_stat.channel_reserve_msat;
6223 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6224 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6225 // The 2* and +1 are for the fee spike reserve.
6226 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6228 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6229 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6230 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6231 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6232 check_added_monitors!(nodes[0], 1);
6233 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6235 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6236 // at this time channel-initiatee receivers are not required to enforce that senders
6237 // respect the fee_spike_reserve.
6238 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6239 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6241 assert!(nodes[1].node.list_channels().is_empty());
6242 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6243 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6244 check_added_monitors!(nodes[1], 1);
6245 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6249 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6250 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6251 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
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);
6256 let chan = 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], 3999999);
6259 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6260 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6261 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6262 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6263 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6264 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6266 let mut msg = msgs::UpdateAddHTLC {
6270 payment_hash: our_payment_hash,
6271 cltv_expiry: htlc_cltv,
6272 onion_routing_packet: onion_packet.clone(),
6275 for i in 0..super::channel::OUR_MAX_HTLCS {
6276 msg.htlc_id = i as u64;
6277 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6279 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6280 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6282 assert!(nodes[1].node.list_channels().is_empty());
6283 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6284 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6285 check_added_monitors!(nodes[1], 1);
6286 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6290 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6291 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6292 let chanmon_cfgs = create_chanmon_cfgs(2);
6293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6296 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6299 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6300 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6301 check_added_monitors!(nodes[0], 1);
6302 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6303 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;
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6306 assert!(nodes[1].node.list_channels().is_empty());
6307 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6308 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6309 check_added_monitors!(nodes[1], 1);
6310 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6314 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6315 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6316 let chanmon_cfgs = create_chanmon_cfgs(2);
6317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6319 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6321 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6322 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6323 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6324 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6325 check_added_monitors!(nodes[0], 1);
6326 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6327 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6328 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6330 assert!(nodes[1].node.list_channels().is_empty());
6331 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6332 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6333 check_added_monitors!(nodes[1], 1);
6334 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6338 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6339 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6340 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6341 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6342 let chanmon_cfgs = create_chanmon_cfgs(2);
6343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6345 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6347 create_announced_chan_between_nodes(&nodes, 0, 1);
6348 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6349 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6350 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6351 check_added_monitors!(nodes[0], 1);
6352 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6355 //Disconnect and Reconnect
6356 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6357 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6358 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();
6359 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6360 assert_eq!(reestablish_1.len(), 1);
6361 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();
6362 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6363 assert_eq!(reestablish_2.len(), 1);
6364 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6365 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6366 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6367 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6370 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6371 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6372 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6373 check_added_monitors!(nodes[1], 1);
6374 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6376 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6378 assert!(nodes[1].node.list_channels().is_empty());
6379 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6380 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6381 check_added_monitors!(nodes[1], 1);
6382 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6386 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6387 //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.
6389 let chanmon_cfgs = create_chanmon_cfgs(2);
6390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6392 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6393 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6394 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6395 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6396 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6398 check_added_monitors!(nodes[0], 1);
6399 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6400 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6402 let update_msg = msgs::UpdateFulfillHTLC{
6405 payment_preimage: our_payment_preimage,
6408 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6410 assert!(nodes[0].node.list_channels().is_empty());
6411 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6412 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()));
6413 check_added_monitors!(nodes[0], 1);
6414 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6418 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6419 //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.
6421 let chanmon_cfgs = create_chanmon_cfgs(2);
6422 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6423 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6424 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6425 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6427 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6428 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6429 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6430 check_added_monitors!(nodes[0], 1);
6431 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6432 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6434 let update_msg = msgs::UpdateFailHTLC{
6437 reason: msgs::OnionErrorPacket { data: Vec::new()},
6440 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6442 assert!(nodes[0].node.list_channels().is_empty());
6443 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6444 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()));
6445 check_added_monitors!(nodes[0], 1);
6446 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6450 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6451 //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.
6453 let chanmon_cfgs = create_chanmon_cfgs(2);
6454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6456 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6457 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6459 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6460 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6461 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6462 check_added_monitors!(nodes[0], 1);
6463 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6464 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6465 let update_msg = msgs::UpdateFailMalformedHTLC{
6468 sha256_of_onion: [1; 32],
6469 failure_code: 0x8000,
6472 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6474 assert!(nodes[0].node.list_channels().is_empty());
6475 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6476 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()));
6477 check_added_monitors!(nodes[0], 1);
6478 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6482 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6483 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6485 let chanmon_cfgs = create_chanmon_cfgs(2);
6486 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6487 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6488 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6489 create_announced_chan_between_nodes(&nodes, 0, 1);
6491 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6493 nodes[1].node.claim_funds(our_payment_preimage);
6494 check_added_monitors!(nodes[1], 1);
6495 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6497 let events = nodes[1].node.get_and_clear_pending_msg_events();
6498 assert_eq!(events.len(), 1);
6499 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6501 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, .. } } => {
6502 assert!(update_add_htlcs.is_empty());
6503 assert_eq!(update_fulfill_htlcs.len(), 1);
6504 assert!(update_fail_htlcs.is_empty());
6505 assert!(update_fail_malformed_htlcs.is_empty());
6506 assert!(update_fee.is_none());
6507 update_fulfill_htlcs[0].clone()
6509 _ => panic!("Unexpected event"),
6513 update_fulfill_msg.htlc_id = 1;
6515 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6517 assert!(nodes[0].node.list_channels().is_empty());
6518 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6519 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6520 check_added_monitors!(nodes[0], 1);
6521 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6525 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6526 //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.
6528 let chanmon_cfgs = create_chanmon_cfgs(2);
6529 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6530 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6531 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6532 create_announced_chan_between_nodes(&nodes, 0, 1);
6534 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6536 nodes[1].node.claim_funds(our_payment_preimage);
6537 check_added_monitors!(nodes[1], 1);
6538 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6540 let events = nodes[1].node.get_and_clear_pending_msg_events();
6541 assert_eq!(events.len(), 1);
6542 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6544 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, .. } } => {
6545 assert!(update_add_htlcs.is_empty());
6546 assert_eq!(update_fulfill_htlcs.len(), 1);
6547 assert!(update_fail_htlcs.is_empty());
6548 assert!(update_fail_malformed_htlcs.is_empty());
6549 assert!(update_fee.is_none());
6550 update_fulfill_htlcs[0].clone()
6552 _ => panic!("Unexpected event"),
6556 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6558 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6560 assert!(nodes[0].node.list_channels().is_empty());
6561 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6562 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6563 check_added_monitors!(nodes[0], 1);
6564 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6568 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6569 //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.
6571 let chanmon_cfgs = create_chanmon_cfgs(2);
6572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6574 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6575 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6577 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6578 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6579 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6580 check_added_monitors!(nodes[0], 1);
6582 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6583 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6585 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6586 check_added_monitors!(nodes[1], 0);
6587 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6589 let events = nodes[1].node.get_and_clear_pending_msg_events();
6591 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6593 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, .. } } => {
6594 assert!(update_add_htlcs.is_empty());
6595 assert!(update_fulfill_htlcs.is_empty());
6596 assert!(update_fail_htlcs.is_empty());
6597 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6598 assert!(update_fee.is_none());
6599 update_fail_malformed_htlcs[0].clone()
6601 _ => panic!("Unexpected event"),
6604 update_msg.failure_code &= !0x8000;
6605 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6607 assert!(nodes[0].node.list_channels().is_empty());
6608 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6609 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6610 check_added_monitors!(nodes[0], 1);
6611 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6615 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6616 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6617 // * 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.
6619 let chanmon_cfgs = create_chanmon_cfgs(3);
6620 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6621 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6622 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6623 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6624 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6626 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6629 let mut payment_event = {
6630 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6631 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6632 check_added_monitors!(nodes[0], 1);
6633 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6634 assert_eq!(events.len(), 1);
6635 SendEvent::from_event(events.remove(0))
6637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6638 check_added_monitors!(nodes[1], 0);
6639 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6640 expect_pending_htlcs_forwardable!(nodes[1]);
6641 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6642 assert_eq!(events_2.len(), 1);
6643 check_added_monitors!(nodes[1], 1);
6644 payment_event = SendEvent::from_event(events_2.remove(0));
6645 assert_eq!(payment_event.msgs.len(), 1);
6648 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6649 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6650 check_added_monitors!(nodes[2], 0);
6651 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6653 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6654 assert_eq!(events_3.len(), 1);
6655 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6657 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 } } => {
6658 assert!(update_add_htlcs.is_empty());
6659 assert!(update_fulfill_htlcs.is_empty());
6660 assert!(update_fail_htlcs.is_empty());
6661 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6662 assert!(update_fee.is_none());
6663 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6665 _ => panic!("Unexpected event"),
6669 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6671 check_added_monitors!(nodes[1], 0);
6672 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6673 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 }]);
6674 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6675 assert_eq!(events_4.len(), 1);
6677 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6679 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, .. } } => {
6680 assert!(update_add_htlcs.is_empty());
6681 assert!(update_fulfill_htlcs.is_empty());
6682 assert_eq!(update_fail_htlcs.len(), 1);
6683 assert!(update_fail_malformed_htlcs.is_empty());
6684 assert!(update_fee.is_none());
6686 _ => panic!("Unexpected event"),
6689 check_added_monitors!(nodes[1], 1);
6693 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6694 let chanmon_cfgs = create_chanmon_cfgs(3);
6695 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6696 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6697 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6698 create_announced_chan_between_nodes(&nodes, 0, 1);
6699 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6701 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6704 let mut payment_event = {
6705 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6706 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6707 check_added_monitors!(nodes[0], 1);
6708 SendEvent::from_node(&nodes[0])
6711 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6712 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6713 expect_pending_htlcs_forwardable!(nodes[1]);
6714 check_added_monitors!(nodes[1], 1);
6715 payment_event = SendEvent::from_node(&nodes[1]);
6716 assert_eq!(payment_event.msgs.len(), 1);
6719 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6720 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6721 check_added_monitors!(nodes[2], 0);
6722 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6724 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6725 assert_eq!(events_3.len(), 1);
6727 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6728 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6729 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6730 update_msg.failure_code |= 0x2000;
6732 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6733 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6735 _ => panic!("Unexpected event"),
6738 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6739 vec![HTLCDestination::NextHopChannel {
6740 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6741 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6742 assert_eq!(events_4.len(), 1);
6743 check_added_monitors!(nodes[1], 1);
6746 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6747 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6748 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6750 _ => panic!("Unexpected event"),
6753 let events_5 = nodes[0].node.get_and_clear_pending_events();
6754 assert_eq!(events_5.len(), 2);
6756 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6757 // the node originating the error to its next hop.
6759 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6761 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6762 assert!(is_permanent);
6763 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6765 _ => panic!("Unexpected event"),
6768 Event::PaymentFailed { payment_hash, .. } => {
6769 assert_eq!(payment_hash, our_payment_hash);
6771 _ => panic!("Unexpected event"),
6774 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6777 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6778 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6779 // 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
6780 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6782 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6783 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6787 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6789 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6790 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6792 // We route 2 dust-HTLCs between A and B
6793 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6794 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6795 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6797 // Cache one local commitment tx as previous
6798 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6800 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6801 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6802 check_added_monitors!(nodes[1], 0);
6803 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6804 check_added_monitors!(nodes[1], 1);
6806 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6807 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6808 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6809 check_added_monitors!(nodes[0], 1);
6811 // Cache one local commitment tx as lastest
6812 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6814 let events = nodes[0].node.get_and_clear_pending_msg_events();
6816 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6817 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6819 _ => panic!("Unexpected event"),
6822 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6823 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6825 _ => panic!("Unexpected event"),
6828 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6829 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6830 if announce_latest {
6831 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6833 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6836 check_closed_broadcast!(nodes[0], true);
6837 check_added_monitors!(nodes[0], 1);
6838 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6840 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6841 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6842 let events = nodes[0].node.get_and_clear_pending_events();
6843 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6844 assert_eq!(events.len(), 4);
6845 let mut first_failed = false;
6846 for event in events {
6848 Event::PaymentPathFailed { payment_hash, .. } => {
6849 if payment_hash == payment_hash_1 {
6850 assert!(!first_failed);
6851 first_failed = true;
6853 assert_eq!(payment_hash, payment_hash_2);
6856 Event::PaymentFailed { .. } => {}
6857 _ => panic!("Unexpected event"),
6863 fn test_failure_delay_dust_htlc_local_commitment() {
6864 do_test_failure_delay_dust_htlc_local_commitment(true);
6865 do_test_failure_delay_dust_htlc_local_commitment(false);
6868 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6869 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6870 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6871 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6872 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6873 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6874 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6876 let chanmon_cfgs = create_chanmon_cfgs(3);
6877 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6878 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6879 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6880 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6882 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6883 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6885 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6886 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6888 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6889 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6891 // We revoked bs_commitment_tx
6893 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6894 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6897 let mut timeout_tx = Vec::new();
6899 // We fail dust-HTLC 1 by broadcast of local commitment tx
6900 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6901 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6902 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6903 expect_payment_failed!(nodes[0], dust_hash, false);
6905 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6906 check_closed_broadcast!(nodes[0], true);
6907 check_added_monitors!(nodes[0], 1);
6908 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6909 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6910 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6911 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6912 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6913 mine_transaction(&nodes[0], &timeout_tx[0]);
6914 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6915 expect_payment_failed!(nodes[0], non_dust_hash, false);
6917 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6918 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6919 check_closed_broadcast!(nodes[0], true);
6920 check_added_monitors!(nodes[0], 1);
6921 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6922 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6924 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6925 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6926 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6927 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6928 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6929 // dust HTLC should have been failed.
6930 expect_payment_failed!(nodes[0], dust_hash, false);
6933 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6935 assert_eq!(timeout_tx[0].lock_time.0, 12);
6937 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6938 mine_transaction(&nodes[0], &timeout_tx[0]);
6939 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6940 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6941 expect_payment_failed!(nodes[0], non_dust_hash, false);
6946 fn test_sweep_outbound_htlc_failure_update() {
6947 do_test_sweep_outbound_htlc_failure_update(false, true);
6948 do_test_sweep_outbound_htlc_failure_update(false, false);
6949 do_test_sweep_outbound_htlc_failure_update(true, false);
6953 fn test_user_configurable_csv_delay() {
6954 // We test our channel constructors yield errors when we pass them absurd csv delay
6956 let mut low_our_to_self_config = UserConfig::default();
6957 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6958 let mut high_their_to_self_config = UserConfig::default();
6959 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6960 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6961 let chanmon_cfgs = create_chanmon_cfgs(2);
6962 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6963 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6964 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6966 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6967 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6968 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6969 &low_our_to_self_config, 0, 42)
6972 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())); },
6973 _ => panic!("Unexpected event"),
6975 } else { assert!(false) }
6977 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6978 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6979 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6980 open_channel.to_self_delay = 200;
6981 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6982 &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,
6983 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6986 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())); },
6987 _ => panic!("Unexpected event"),
6989 } else { assert!(false); }
6991 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6992 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6993 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()));
6994 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6995 accept_channel.to_self_delay = 200;
6996 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6998 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7000 &ErrorAction::SendErrorMessage { ref msg } => {
7001 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()));
7002 reason_msg = msg.data.clone();
7006 } else { panic!(); }
7007 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7009 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7010 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7011 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7012 open_channel.to_self_delay = 200;
7013 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7014 &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,
7015 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7018 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())); },
7019 _ => panic!("Unexpected event"),
7021 } else { assert!(false); }
7025 fn test_check_htlc_underpaying() {
7026 // Send payment through A -> B but A is maliciously
7027 // sending a probe payment (i.e less than expected value0
7028 // to B, B should refuse payment.
7030 let chanmon_cfgs = create_chanmon_cfgs(2);
7031 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7032 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7033 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7035 // Create some initial channels
7036 create_announced_chan_between_nodes(&nodes, 0, 1);
7038 let scorer = test_utils::TestScorer::new();
7039 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7040 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
7041 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();
7042 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7043 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7044 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7045 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7046 check_added_monitors!(nodes[0], 1);
7048 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7049 assert_eq!(events.len(), 1);
7050 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7051 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7052 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7054 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7055 // and then will wait a second random delay before failing the HTLC back:
7056 expect_pending_htlcs_forwardable!(nodes[1]);
7057 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7059 // Node 3 is expecting payment of 100_000 but received 10_000,
7060 // it should fail htlc like we didn't know the preimage.
7061 nodes[1].node.process_pending_htlc_forwards();
7063 let events = nodes[1].node.get_and_clear_pending_msg_events();
7064 assert_eq!(events.len(), 1);
7065 let (update_fail_htlc, commitment_signed) = match events[0] {
7066 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 } } => {
7067 assert!(update_add_htlcs.is_empty());
7068 assert!(update_fulfill_htlcs.is_empty());
7069 assert_eq!(update_fail_htlcs.len(), 1);
7070 assert!(update_fail_malformed_htlcs.is_empty());
7071 assert!(update_fee.is_none());
7072 (update_fail_htlcs[0].clone(), commitment_signed)
7074 _ => panic!("Unexpected event"),
7076 check_added_monitors!(nodes[1], 1);
7078 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7079 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7081 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7082 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7083 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7084 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7088 fn test_announce_disable_channels() {
7089 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7090 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7092 let chanmon_cfgs = create_chanmon_cfgs(2);
7093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7097 create_announced_chan_between_nodes(&nodes, 0, 1);
7098 create_announced_chan_between_nodes(&nodes, 1, 0);
7099 create_announced_chan_between_nodes(&nodes, 0, 1);
7102 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7103 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7105 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7106 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7107 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7108 assert_eq!(msg_events.len(), 3);
7109 let mut chans_disabled = HashMap::new();
7110 for e in msg_events {
7112 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7113 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7114 // Check that each channel gets updated exactly once
7115 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7116 panic!("Generated ChannelUpdate for wrong chan!");
7119 _ => panic!("Unexpected event"),
7123 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();
7124 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7125 assert_eq!(reestablish_1.len(), 3);
7126 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();
7127 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7128 assert_eq!(reestablish_2.len(), 3);
7130 // Reestablish chan_1
7131 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7132 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7133 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7134 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7135 // Reestablish chan_2
7136 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7137 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7138 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7139 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7140 // Reestablish chan_3
7141 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7142 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7143 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7144 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7146 nodes[0].node.timer_tick_occurred();
7147 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7148 nodes[0].node.timer_tick_occurred();
7149 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7150 assert_eq!(msg_events.len(), 3);
7151 for e in msg_events {
7153 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7154 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7155 match chans_disabled.remove(&msg.contents.short_channel_id) {
7156 // Each update should have a higher timestamp than the previous one, replacing
7158 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7159 None => panic!("Generated ChannelUpdate for wrong chan!"),
7162 _ => panic!("Unexpected event"),
7165 // Check that each channel gets updated exactly once
7166 assert!(chans_disabled.is_empty());
7170 fn test_bump_penalty_txn_on_revoked_commitment() {
7171 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7172 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7174 let chanmon_cfgs = create_chanmon_cfgs(2);
7175 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7176 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7177 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7179 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7181 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7182 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7183 .with_features(nodes[0].node.invoice_features());
7184 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7185 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7187 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7188 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7189 assert_eq!(revoked_txn[0].output.len(), 4);
7190 assert_eq!(revoked_txn[0].input.len(), 1);
7191 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7192 let revoked_txid = revoked_txn[0].txid();
7194 let mut penalty_sum = 0;
7195 for outp in revoked_txn[0].output.iter() {
7196 if outp.script_pubkey.is_v0_p2wsh() {
7197 penalty_sum += outp.value;
7201 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7202 let header_114 = connect_blocks(&nodes[1], 14);
7204 // Actually revoke tx by claiming a HTLC
7205 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7206 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7207 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7208 check_added_monitors!(nodes[1], 1);
7210 // One or more justice tx should have been broadcast, check it
7214 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7215 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7216 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7217 assert_eq!(node_txn[0].output.len(), 1);
7218 check_spends!(node_txn[0], revoked_txn[0]);
7219 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7220 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7221 penalty_1 = node_txn[0].txid();
7225 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7226 connect_blocks(&nodes[1], 15);
7227 let mut penalty_2 = penalty_1;
7228 let mut feerate_2 = 0;
7230 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7231 assert_eq!(node_txn.len(), 1);
7232 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7233 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7234 assert_eq!(node_txn[0].output.len(), 1);
7235 check_spends!(node_txn[0], revoked_txn[0]);
7236 penalty_2 = node_txn[0].txid();
7237 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7238 assert_ne!(penalty_2, penalty_1);
7239 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7240 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7241 // Verify 25% bump heuristic
7242 assert!(feerate_2 * 100 >= feerate_1 * 125);
7246 assert_ne!(feerate_2, 0);
7248 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7249 connect_blocks(&nodes[1], 1);
7251 let mut feerate_3 = 0;
7253 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7254 assert_eq!(node_txn.len(), 1);
7255 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7256 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7257 assert_eq!(node_txn[0].output.len(), 1);
7258 check_spends!(node_txn[0], revoked_txn[0]);
7259 penalty_3 = node_txn[0].txid();
7260 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7261 assert_ne!(penalty_3, penalty_2);
7262 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7263 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7264 // Verify 25% bump heuristic
7265 assert!(feerate_3 * 100 >= feerate_2 * 125);
7269 assert_ne!(feerate_3, 0);
7271 nodes[1].node.get_and_clear_pending_events();
7272 nodes[1].node.get_and_clear_pending_msg_events();
7276 fn test_bump_penalty_txn_on_revoked_htlcs() {
7277 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7278 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7280 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7281 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7284 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7286 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7287 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7288 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7289 let scorer = test_utils::TestScorer::new();
7290 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7291 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7292 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7293 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7294 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7295 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7296 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7297 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7299 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7300 assert_eq!(revoked_local_txn[0].input.len(), 1);
7301 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7303 // Revoke local commitment tx
7304 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7306 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7307 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7308 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7309 check_closed_broadcast!(nodes[1], true);
7310 check_added_monitors!(nodes[1], 1);
7311 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7312 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7314 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7315 assert_eq!(revoked_htlc_txn.len(), 2);
7317 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7318 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7319 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7321 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7322 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7323 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7324 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7326 // Broadcast set of revoked txn on A
7327 let hash_128 = connect_blocks(&nodes[0], 40);
7328 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7329 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7330 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7331 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7332 let events = nodes[0].node.get_and_clear_pending_events();
7333 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7334 match events.last().unwrap() {
7335 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7336 _ => panic!("Unexpected event"),
7342 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7343 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7344 // Verify claim tx are spending revoked HTLC txn
7346 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7347 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7348 // which are included in the same block (they are broadcasted because we scan the
7349 // transactions linearly and generate claims as we go, they likely should be removed in the
7351 assert_eq!(node_txn[0].input.len(), 1);
7352 check_spends!(node_txn[0], revoked_local_txn[0]);
7353 assert_eq!(node_txn[1].input.len(), 1);
7354 check_spends!(node_txn[1], revoked_local_txn[0]);
7355 assert_eq!(node_txn[2].input.len(), 1);
7356 check_spends!(node_txn[2], revoked_local_txn[0]);
7358 // Each of the three justice transactions claim a separate (single) output of the three
7359 // available, which we check here:
7360 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7361 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7362 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7364 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7365 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7367 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7368 // output, checked above).
7369 assert_eq!(node_txn[3].input.len(), 2);
7370 assert_eq!(node_txn[3].output.len(), 1);
7371 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7373 first = node_txn[3].txid();
7374 // Store both feerates for later comparison
7375 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7376 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7377 penalty_txn = vec![node_txn[2].clone()];
7381 // Connect one more block to see if bumped penalty are issued for HTLC txn
7382 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7383 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7384 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7385 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7387 // Few more blocks to confirm penalty txn
7388 connect_blocks(&nodes[0], 4);
7389 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7390 let header_144 = connect_blocks(&nodes[0], 9);
7392 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7393 assert_eq!(node_txn.len(), 1);
7395 assert_eq!(node_txn[0].input.len(), 2);
7396 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7397 // Verify bumped tx is different and 25% bump heuristic
7398 assert_ne!(first, node_txn[0].txid());
7399 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7400 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7401 assert!(feerate_2 * 100 > feerate_1 * 125);
7402 let txn = vec![node_txn[0].clone()];
7406 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7407 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7408 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7409 connect_blocks(&nodes[0], 20);
7411 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7412 // We verify than no new transaction has been broadcast because previously
7413 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7414 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7415 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7416 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7417 // up bumped justice generation.
7418 assert_eq!(node_txn.len(), 0);
7421 check_closed_broadcast!(nodes[0], true);
7422 check_added_monitors!(nodes[0], 1);
7426 fn test_bump_penalty_txn_on_remote_commitment() {
7427 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7428 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7431 // Provide preimage for one
7432 // Check aggregation
7434 let chanmon_cfgs = create_chanmon_cfgs(2);
7435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7437 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7439 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7440 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7441 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7443 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7444 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7445 assert_eq!(remote_txn[0].output.len(), 4);
7446 assert_eq!(remote_txn[0].input.len(), 1);
7447 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7449 // Claim a HTLC without revocation (provide B monitor with preimage)
7450 nodes[1].node.claim_funds(payment_preimage);
7451 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7452 mine_transaction(&nodes[1], &remote_txn[0]);
7453 check_added_monitors!(nodes[1], 2);
7454 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7456 // One or more claim tx should have been broadcast, check it
7460 let feerate_timeout;
7461 let feerate_preimage;
7463 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7464 // 3 transactions including:
7465 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7466 assert_eq!(node_txn.len(), 3);
7467 assert_eq!(node_txn[0].input.len(), 1);
7468 assert_eq!(node_txn[1].input.len(), 1);
7469 assert_eq!(node_txn[2].input.len(), 1);
7470 check_spends!(node_txn[0], remote_txn[0]);
7471 check_spends!(node_txn[1], remote_txn[0]);
7472 check_spends!(node_txn[2], remote_txn[0]);
7474 preimage = node_txn[0].txid();
7475 let index = node_txn[0].input[0].previous_output.vout;
7476 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7477 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7479 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7480 (node_txn[2].clone(), node_txn[1].clone())
7482 (node_txn[1].clone(), node_txn[2].clone())
7485 preimage_bump = preimage_bump_tx;
7486 check_spends!(preimage_bump, remote_txn[0]);
7487 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7489 timeout = timeout_tx.txid();
7490 let index = timeout_tx.input[0].previous_output.vout;
7491 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7492 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7496 assert_ne!(feerate_timeout, 0);
7497 assert_ne!(feerate_preimage, 0);
7499 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7500 connect_blocks(&nodes[1], 15);
7502 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7503 assert_eq!(node_txn.len(), 1);
7504 assert_eq!(node_txn[0].input.len(), 1);
7505 assert_eq!(preimage_bump.input.len(), 1);
7506 check_spends!(node_txn[0], remote_txn[0]);
7507 check_spends!(preimage_bump, remote_txn[0]);
7509 let index = preimage_bump.input[0].previous_output.vout;
7510 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7511 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7512 assert!(new_feerate * 100 > feerate_timeout * 125);
7513 assert_ne!(timeout, preimage_bump.txid());
7515 let index = node_txn[0].input[0].previous_output.vout;
7516 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7517 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7518 assert!(new_feerate * 100 > feerate_preimage * 125);
7519 assert_ne!(preimage, node_txn[0].txid());
7524 nodes[1].node.get_and_clear_pending_events();
7525 nodes[1].node.get_and_clear_pending_msg_events();
7529 fn test_counterparty_raa_skip_no_crash() {
7530 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7531 // commitment transaction, we would have happily carried on and provided them the next
7532 // commitment transaction based on one RAA forward. This would probably eventually have led to
7533 // channel closure, but it would not have resulted in funds loss. Still, our
7534 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7535 // check simply that the channel is closed in response to such an RAA, but don't check whether
7536 // we decide to punish our counterparty for revoking their funds (as we don't currently
7538 let chanmon_cfgs = create_chanmon_cfgs(2);
7539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7542 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7544 let per_commitment_secret;
7545 let next_per_commitment_point;
7547 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7548 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7549 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7551 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7553 // Make signer believe we got a counterparty signature, so that it allows the revocation
7554 keys.get_enforcement_state().last_holder_commitment -= 1;
7555 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7557 // Must revoke without gaps
7558 keys.get_enforcement_state().last_holder_commitment -= 1;
7559 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7561 keys.get_enforcement_state().last_holder_commitment -= 1;
7562 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7563 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7566 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7567 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7568 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7569 check_added_monitors!(nodes[1], 1);
7570 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7574 fn test_bump_txn_sanitize_tracking_maps() {
7575 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7576 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7578 let chanmon_cfgs = create_chanmon_cfgs(2);
7579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7583 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7584 // Lock HTLC in both directions
7585 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7586 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7588 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7589 assert_eq!(revoked_local_txn[0].input.len(), 1);
7590 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7592 // Revoke local commitment tx
7593 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7595 // Broadcast set of revoked txn on A
7596 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7597 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7598 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7600 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7601 check_closed_broadcast!(nodes[0], true);
7602 check_added_monitors!(nodes[0], 1);
7603 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7605 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7606 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7607 check_spends!(node_txn[0], revoked_local_txn[0]);
7608 check_spends!(node_txn[1], revoked_local_txn[0]);
7609 check_spends!(node_txn[2], revoked_local_txn[0]);
7610 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7614 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7615 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7616 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7618 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7619 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7620 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7625 fn test_pending_claimed_htlc_no_balance_underflow() {
7626 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7627 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7628 let chanmon_cfgs = create_chanmon_cfgs(2);
7629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7632 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7634 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7635 nodes[1].node.claim_funds(payment_preimage);
7636 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7637 check_added_monitors!(nodes[1], 1);
7638 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7640 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7641 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7642 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7643 check_added_monitors!(nodes[0], 1);
7644 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7646 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7647 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7648 // can get our balance.
7650 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7651 // the public key of the only hop. This works around ChannelDetails not showing the
7652 // almost-claimed HTLC as available balance.
7653 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7654 route.payment_params = None; // This is all wrong, but unnecessary
7655 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7656 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7657 nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7658 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7660 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7664 fn test_channel_conf_timeout() {
7665 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7666 // confirm within 2016 blocks, as recommended by BOLT 2.
7667 let chanmon_cfgs = create_chanmon_cfgs(2);
7668 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7669 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7670 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7672 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7674 // The outbound node should wait forever for confirmation:
7675 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7676 // copied here instead of directly referencing the constant.
7677 connect_blocks(&nodes[0], 2016);
7678 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7680 // The inbound node should fail the channel after exactly 2016 blocks
7681 connect_blocks(&nodes[1], 2015);
7682 check_added_monitors!(nodes[1], 0);
7683 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7685 connect_blocks(&nodes[1], 1);
7686 check_added_monitors!(nodes[1], 1);
7687 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7688 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7689 assert_eq!(close_ev.len(), 1);
7691 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7692 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7693 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7695 _ => panic!("Unexpected event"),
7700 fn test_override_channel_config() {
7701 let chanmon_cfgs = create_chanmon_cfgs(2);
7702 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7703 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7704 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7706 // Node0 initiates a channel to node1 using the override config.
7707 let mut override_config = UserConfig::default();
7708 override_config.channel_handshake_config.our_to_self_delay = 200;
7710 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7712 // Assert the channel created by node0 is using the override config.
7713 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7714 assert_eq!(res.channel_flags, 0);
7715 assert_eq!(res.to_self_delay, 200);
7719 fn test_override_0msat_htlc_minimum() {
7720 let mut zero_config = UserConfig::default();
7721 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7722 let chanmon_cfgs = create_chanmon_cfgs(2);
7723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7727 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7728 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7729 assert_eq!(res.htlc_minimum_msat, 1);
7731 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7732 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7733 assert_eq!(res.htlc_minimum_msat, 1);
7737 fn test_channel_update_has_correct_htlc_maximum_msat() {
7738 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7739 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7740 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7741 // 90% of the `channel_value`.
7742 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7744 let mut config_30_percent = UserConfig::default();
7745 config_30_percent.channel_handshake_config.announced_channel = true;
7746 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7747 let mut config_50_percent = UserConfig::default();
7748 config_50_percent.channel_handshake_config.announced_channel = true;
7749 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7750 let mut config_95_percent = UserConfig::default();
7751 config_95_percent.channel_handshake_config.announced_channel = true;
7752 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7753 let mut config_100_percent = UserConfig::default();
7754 config_100_percent.channel_handshake_config.announced_channel = true;
7755 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7757 let chanmon_cfgs = create_chanmon_cfgs(4);
7758 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7759 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)]);
7760 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7762 let channel_value_satoshis = 100000;
7763 let channel_value_msat = channel_value_satoshis * 1000;
7764 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7765 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7766 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7768 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7769 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7771 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7772 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7773 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7774 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7775 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7776 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7778 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7779 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7781 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7782 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7783 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7785 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7789 fn test_manually_accept_inbound_channel_request() {
7790 let mut manually_accept_conf = UserConfig::default();
7791 manually_accept_conf.manually_accept_inbound_channels = true;
7792 let chanmon_cfgs = create_chanmon_cfgs(2);
7793 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7794 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7795 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7797 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7798 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7800 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7802 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7803 // accepting the inbound channel request.
7804 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7806 let events = nodes[1].node.get_and_clear_pending_events();
7808 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7809 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7811 _ => panic!("Unexpected event"),
7814 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7815 assert_eq!(accept_msg_ev.len(), 1);
7817 match accept_msg_ev[0] {
7818 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7819 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7821 _ => panic!("Unexpected event"),
7824 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7826 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7827 assert_eq!(close_msg_ev.len(), 1);
7829 let events = nodes[1].node.get_and_clear_pending_events();
7831 Event::ChannelClosed { user_channel_id, .. } => {
7832 assert_eq!(user_channel_id, 23);
7834 _ => panic!("Unexpected event"),
7839 fn test_manually_reject_inbound_channel_request() {
7840 let mut manually_accept_conf = UserConfig::default();
7841 manually_accept_conf.manually_accept_inbound_channels = true;
7842 let chanmon_cfgs = create_chanmon_cfgs(2);
7843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7847 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7848 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7850 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7852 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7853 // rejecting the inbound channel request.
7854 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7856 let events = nodes[1].node.get_and_clear_pending_events();
7858 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7859 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7861 _ => panic!("Unexpected event"),
7864 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7865 assert_eq!(close_msg_ev.len(), 1);
7867 match close_msg_ev[0] {
7868 MessageSendEvent::HandleError { ref node_id, .. } => {
7869 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7871 _ => panic!("Unexpected event"),
7873 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7877 fn test_reject_funding_before_inbound_channel_accepted() {
7878 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7879 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7880 // the node operator before the counterparty sends a `FundingCreated` message. If a
7881 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7882 // and the channel should be closed.
7883 let mut manually_accept_conf = UserConfig::default();
7884 manually_accept_conf.manually_accept_inbound_channels = true;
7885 let chanmon_cfgs = create_chanmon_cfgs(2);
7886 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7887 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7888 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7890 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7891 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7892 let temp_channel_id = res.temporary_channel_id;
7894 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7896 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7897 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7899 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7900 nodes[1].node.get_and_clear_pending_events();
7902 // Get the `AcceptChannel` message of `nodes[1]` without calling
7903 // `ChannelManager::accept_inbound_channel`, which generates a
7904 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7905 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7906 // succeed when `nodes[0]` is passed to it.
7907 let accept_chan_msg = {
7908 let mut node_1_per_peer_lock;
7909 let mut node_1_peer_state_lock;
7910 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7911 channel.get_accept_channel_message()
7913 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7915 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7917 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7918 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7920 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7921 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7923 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7924 assert_eq!(close_msg_ev.len(), 1);
7926 let expected_err = "FundingCreated message received before the channel was accepted";
7927 match close_msg_ev[0] {
7928 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7929 assert_eq!(msg.channel_id, temp_channel_id);
7930 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7931 assert_eq!(msg.data, expected_err);
7933 _ => panic!("Unexpected event"),
7936 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7940 fn test_can_not_accept_inbound_channel_twice() {
7941 let mut manually_accept_conf = UserConfig::default();
7942 manually_accept_conf.manually_accept_inbound_channels = true;
7943 let chanmon_cfgs = create_chanmon_cfgs(2);
7944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7946 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7948 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7949 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7951 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7953 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7954 // accepting the inbound channel request.
7955 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7957 let events = nodes[1].node.get_and_clear_pending_events();
7959 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7960 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7961 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7963 Err(APIError::APIMisuseError { err }) => {
7964 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7966 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7967 Err(_) => panic!("Unexpected Error"),
7970 _ => panic!("Unexpected event"),
7973 // Ensure that the channel wasn't closed after attempting to accept it twice.
7974 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7975 assert_eq!(accept_msg_ev.len(), 1);
7977 match accept_msg_ev[0] {
7978 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7979 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7981 _ => panic!("Unexpected event"),
7986 fn test_can_not_accept_unknown_inbound_channel() {
7987 let chanmon_cfg = create_chanmon_cfgs(2);
7988 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7989 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7990 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7992 let unknown_channel_id = [0; 32];
7993 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7995 Err(APIError::ChannelUnavailable { err }) => {
7996 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()));
7998 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7999 Err(_) => panic!("Unexpected Error"),
8004 fn test_onion_value_mpp_set_calculation() {
8005 // Test that we use the onion value `amt_to_forward` when
8006 // calculating whether we've reached the `total_msat` of an MPP
8007 // by having a routing node forward more than `amt_to_forward`
8008 // and checking that the receiving node doesn't generate
8009 // a PaymentClaimable event too early
8011 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8012 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8013 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8014 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8016 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8017 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8018 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8019 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8021 let total_msat = 100_000;
8022 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8023 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8024 let sample_path = route.paths.pop().unwrap();
8026 let mut path_1 = sample_path.clone();
8027 path_1[0].pubkey = nodes[1].node.get_our_node_id();
8028 path_1[0].short_channel_id = chan_1_id;
8029 path_1[1].pubkey = nodes[3].node.get_our_node_id();
8030 path_1[1].short_channel_id = chan_3_id;
8031 path_1[1].fee_msat = 100_000;
8032 route.paths.push(path_1);
8034 let mut path_2 = sample_path.clone();
8035 path_2[0].pubkey = nodes[2].node.get_our_node_id();
8036 path_2[0].short_channel_id = chan_2_id;
8037 path_2[1].pubkey = nodes[3].node.get_our_node_id();
8038 path_2[1].short_channel_id = chan_4_id;
8039 path_2[1].fee_msat = 1_000;
8040 route.paths.push(path_2);
8043 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8044 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8045 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8046 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8047 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8048 check_added_monitors!(nodes[0], expected_paths.len());
8050 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8051 assert_eq!(events.len(), expected_paths.len());
8054 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8055 let mut payment_event = SendEvent::from_event(ev);
8056 let mut prev_node = &nodes[0];
8058 for (idx, &node) in expected_paths[0].iter().enumerate() {
8059 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8061 if idx == 0 { // routing node
8062 let session_priv = [3; 32];
8063 let height = nodes[0].best_block_info().1;
8064 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8065 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8066 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8067 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8068 // Edit amt_to_forward to simulate the sender having set
8069 // the final amount and the routing node taking less fee
8070 onion_payloads[1].amt_to_forward = 99_000;
8071 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8072 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8075 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8076 check_added_monitors!(node, 0);
8077 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8078 expect_pending_htlcs_forwardable!(node);
8081 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8082 assert_eq!(events_2.len(), 1);
8083 check_added_monitors!(node, 1);
8084 payment_event = SendEvent::from_event(events_2.remove(0));
8085 assert_eq!(payment_event.msgs.len(), 1);
8087 let events_2 = node.node.get_and_clear_pending_events();
8088 assert!(events_2.is_empty());
8095 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8096 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8098 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8101 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8103 let routing_node_count = msat_amounts.len();
8104 let node_count = routing_node_count + 2;
8106 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8107 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8108 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8109 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8114 // Create channels for each amount
8115 let mut expected_paths = Vec::with_capacity(routing_node_count);
8116 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8117 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8118 for i in 0..routing_node_count {
8119 let routing_node = 2 + i;
8120 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8121 src_chan_ids.push(src_chan_id);
8122 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8123 dst_chan_ids.push(dst_chan_id);
8124 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8125 expected_paths.push(path);
8127 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8129 // Create a route for each amount
8130 let example_amount = 100000;
8131 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[src_idx], nodes[dst_idx], example_amount);
8132 let sample_path = route.paths.pop().unwrap();
8133 for i in 0..routing_node_count {
8134 let routing_node = 2 + i;
8135 let mut path = sample_path.clone();
8136 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8137 path[0].short_channel_id = src_chan_ids[i];
8138 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8139 path[1].short_channel_id = dst_chan_ids[i];
8140 path[1].fee_msat = msat_amounts[i];
8141 route.paths.push(path);
8144 // Send payment with manually set total_msat
8145 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8146 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8147 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8148 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8149 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8150 check_added_monitors!(nodes[src_idx], expected_paths.len());
8152 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8153 assert_eq!(events.len(), expected_paths.len());
8154 let mut amount_received = 0;
8155 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8156 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8158 let current_path_amount = msat_amounts[path_idx];
8159 amount_received += current_path_amount;
8160 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8161 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8164 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8168 fn test_overshoot_mpp() {
8169 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8170 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8174 fn test_simple_mpp() {
8175 // Simple test of sending a multi-path payment.
8176 let chanmon_cfgs = create_chanmon_cfgs(4);
8177 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8178 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8179 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8181 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8182 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8183 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8184 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8186 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8187 let path = route.paths[0].clone();
8188 route.paths.push(path);
8189 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8190 route.paths[0][0].short_channel_id = chan_1_id;
8191 route.paths[0][1].short_channel_id = chan_3_id;
8192 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8193 route.paths[1][0].short_channel_id = chan_2_id;
8194 route.paths[1][1].short_channel_id = chan_4_id;
8195 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8196 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8200 fn test_preimage_storage() {
8201 // Simple test of payment preimage storage allowing no client-side storage to claim payments
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 nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8207 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8210 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8211 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8212 nodes[0].node.send_payment_with_route(&route, payment_hash,
8213 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8214 check_added_monitors!(nodes[0], 1);
8215 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8216 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8218 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8220 // Note that after leaving the above scope we have no knowledge of any arguments or return
8221 // values from previous calls.
8222 expect_pending_htlcs_forwardable!(nodes[1]);
8223 let events = nodes[1].node.get_and_clear_pending_events();
8224 assert_eq!(events.len(), 1);
8226 Event::PaymentClaimable { ref purpose, .. } => {
8228 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8229 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8231 _ => panic!("expected PaymentPurpose::InvoicePayment")
8234 _ => panic!("Unexpected event"),
8239 #[allow(deprecated)]
8240 fn test_secret_timeout() {
8241 // Simple test of payment secret storage time outs. After
8242 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8243 let chanmon_cfgs = create_chanmon_cfgs(2);
8244 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8245 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8246 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8248 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8250 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8252 // We should fail to register the same payment hash twice, at least until we've connected a
8253 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8254 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8255 assert_eq!(err, "Duplicate payment hash");
8256 } else { panic!(); }
8258 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8260 header: BlockHeader {
8262 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8263 merkle_root: TxMerkleNode::all_zeros(),
8264 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8268 connect_block(&nodes[1], &block);
8269 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8270 assert_eq!(err, "Duplicate payment hash");
8271 } else { panic!(); }
8273 // If we then connect the second block, we should be able to register the same payment hash
8274 // again (this time getting a new payment secret).
8275 block.header.prev_blockhash = block.header.block_hash();
8276 block.header.time += 1;
8277 connect_block(&nodes[1], &block);
8278 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8279 assert_ne!(payment_secret_1, our_payment_secret);
8282 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8283 nodes[0].node.send_payment_with_route(&route, payment_hash,
8284 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8285 check_added_monitors!(nodes[0], 1);
8286 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8287 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8288 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8289 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8291 // Note that after leaving the above scope we have no knowledge of any arguments or return
8292 // values from previous calls.
8293 expect_pending_htlcs_forwardable!(nodes[1]);
8294 let events = nodes[1].node.get_and_clear_pending_events();
8295 assert_eq!(events.len(), 1);
8297 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8298 assert!(payment_preimage.is_none());
8299 assert_eq!(payment_secret, our_payment_secret);
8300 // We don't actually have the payment preimage with which to claim this payment!
8302 _ => panic!("Unexpected event"),
8307 fn test_bad_secret_hash() {
8308 // Simple test of unregistered payment hash/invalid payment secret handling
8309 let chanmon_cfgs = create_chanmon_cfgs(2);
8310 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8311 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8312 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8314 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8316 let random_payment_hash = PaymentHash([42; 32]);
8317 let random_payment_secret = PaymentSecret([43; 32]);
8318 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8319 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8321 // All the below cases should end up being handled exactly identically, so we macro the
8322 // resulting events.
8323 macro_rules! handle_unknown_invalid_payment_data {
8324 ($payment_hash: expr) => {
8325 check_added_monitors!(nodes[0], 1);
8326 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8327 let payment_event = SendEvent::from_event(events.pop().unwrap());
8328 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8329 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8331 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8332 // again to process the pending backwards-failure of the HTLC
8333 expect_pending_htlcs_forwardable!(nodes[1]);
8334 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8335 check_added_monitors!(nodes[1], 1);
8337 // We should fail the payment back
8338 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8339 match events.pop().unwrap() {
8340 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8341 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8342 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8344 _ => panic!("Unexpected event"),
8349 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8350 // Error data is the HTLC value (100,000) and current block height
8351 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8353 // Send a payment with the right payment hash but the wrong payment secret
8354 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8355 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8356 handle_unknown_invalid_payment_data!(our_payment_hash);
8357 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8359 // Send a payment with a random payment hash, but the right payment secret
8360 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8361 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8362 handle_unknown_invalid_payment_data!(random_payment_hash);
8363 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8365 // Send a payment with a random payment hash and random payment secret
8366 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8367 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8368 handle_unknown_invalid_payment_data!(random_payment_hash);
8369 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8373 fn test_update_err_monitor_lockdown() {
8374 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8375 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8376 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8379 // This scenario may happen in a watchtower setup, where watchtower process a block height
8380 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8381 // commitment at same time.
8383 let chanmon_cfgs = create_chanmon_cfgs(2);
8384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8386 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8388 // Create some initial channel
8389 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8390 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8392 // Rebalance the network to generate htlc in the two directions
8393 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8395 // Route a HTLC from node 0 to node 1 (but don't settle)
8396 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8398 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8399 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8400 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8401 let persister = test_utils::TestPersister::new();
8404 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8405 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8406 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8407 assert!(new_monitor == *monitor);
8410 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);
8411 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8414 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8415 let block = Block { header, txdata: vec![] };
8416 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8417 // transaction lock time requirements here.
8418 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8419 watchtower.chain_monitor.block_connected(&block, 200);
8421 // Try to update ChannelMonitor
8422 nodes[1].node.claim_funds(preimage);
8423 check_added_monitors!(nodes[1], 1);
8424 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8426 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8427 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8428 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8430 let mut node_0_per_peer_lock;
8431 let mut node_0_peer_state_lock;
8432 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8433 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8434 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8435 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8436 } else { assert!(false); }
8438 // Our local monitor is in-sync and hasn't processed yet timeout
8439 check_added_monitors!(nodes[0], 1);
8440 let events = nodes[0].node.get_and_clear_pending_events();
8441 assert_eq!(events.len(), 1);
8445 fn test_concurrent_monitor_claim() {
8446 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8447 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8448 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8449 // state N+1 confirms. Alice claims output from state N+1.
8451 let chanmon_cfgs = create_chanmon_cfgs(2);
8452 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8453 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8454 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8456 // Create some initial channel
8457 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8458 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8460 // Rebalance the network to generate htlc in the two directions
8461 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8463 // Route a HTLC from node 0 to node 1 (but don't settle)
8464 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8466 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8467 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8468 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8469 let persister = test_utils::TestPersister::new();
8470 let watchtower_alice = {
8472 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8473 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8474 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8475 assert!(new_monitor == *monitor);
8478 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);
8479 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8482 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8483 let block = Block { header, txdata: vec![] };
8484 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8485 // transaction lock time requirements here.
8486 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));
8487 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8489 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8491 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8492 assert_eq!(txn.len(), 2);
8496 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8497 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8498 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8499 let persister = test_utils::TestPersister::new();
8500 let watchtower_bob = {
8502 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8503 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8504 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8505 assert!(new_monitor == *monitor);
8508 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);
8509 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8512 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8513 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8515 // Route another payment to generate another update with still previous HTLC pending
8516 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8517 nodes[1].node.send_payment_with_route(&route, payment_hash,
8518 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8519 check_added_monitors!(nodes[1], 1);
8521 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8522 assert_eq!(updates.update_add_htlcs.len(), 1);
8523 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8525 let mut node_0_per_peer_lock;
8526 let mut node_0_peer_state_lock;
8527 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8528 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8529 // Watchtower Alice should already have seen the block and reject the update
8530 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8531 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8532 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8533 } else { assert!(false); }
8535 // Our local monitor is in-sync and hasn't processed yet timeout
8536 check_added_monitors!(nodes[0], 1);
8538 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8539 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8540 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8542 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8545 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8546 assert_eq!(txn.len(), 2);
8547 bob_state_y = txn[0].clone();
8551 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8552 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8553 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);
8555 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8556 assert_eq!(htlc_txn.len(), 1);
8557 check_spends!(htlc_txn[0], bob_state_y);
8562 fn test_pre_lockin_no_chan_closed_update() {
8563 // Test that if a peer closes a channel in response to a funding_created message we don't
8564 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8567 // Doing so would imply a channel monitor update before the initial channel monitor
8568 // registration, violating our API guarantees.
8570 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8571 // then opening a second channel with the same funding output as the first (which is not
8572 // rejected because the first channel does not exist in the ChannelManager) and closing it
8573 // before receiving funding_signed.
8574 let chanmon_cfgs = create_chanmon_cfgs(2);
8575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8579 // Create an initial channel
8580 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8581 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8582 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8583 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8584 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8586 // Move the first channel through the funding flow...
8587 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8589 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8590 check_added_monitors!(nodes[0], 0);
8592 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8593 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8594 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8595 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8596 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8600 fn test_htlc_no_detection() {
8601 // This test is a mutation to underscore the detection logic bug we had
8602 // before #653. HTLC value routed is above the remaining balance, thus
8603 // inverting HTLC and `to_remote` output. HTLC will come second and
8604 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8605 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8606 // outputs order detection for correct spending children filtring.
8608 let chanmon_cfgs = create_chanmon_cfgs(2);
8609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8613 // Create some initial channels
8614 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8616 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8617 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8618 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8619 assert_eq!(local_txn[0].input.len(), 1);
8620 assert_eq!(local_txn[0].output.len(), 3);
8621 check_spends!(local_txn[0], chan_1.3);
8623 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8624 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8625 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8626 // We deliberately connect the local tx twice as this should provoke a failure calling
8627 // this test before #653 fix.
8628 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);
8629 check_closed_broadcast!(nodes[0], true);
8630 check_added_monitors!(nodes[0], 1);
8631 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8632 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8634 let htlc_timeout = {
8635 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8636 assert_eq!(node_txn.len(), 1);
8637 assert_eq!(node_txn[0].input.len(), 1);
8638 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8639 check_spends!(node_txn[0], local_txn[0]);
8643 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8644 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8645 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8646 expect_payment_failed!(nodes[0], our_payment_hash, false);
8649 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8650 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8651 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8652 // Carol, Alice would be the upstream node, and Carol the downstream.)
8654 // Steps of the test:
8655 // 1) Alice sends a HTLC to Carol through Bob.
8656 // 2) Carol doesn't settle the HTLC.
8657 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8658 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8659 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8660 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8661 // 5) Carol release the preimage to Bob off-chain.
8662 // 6) Bob claims the offered output on the broadcasted commitment.
8663 let chanmon_cfgs = create_chanmon_cfgs(3);
8664 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8665 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8666 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8668 // Create some initial channels
8669 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8670 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8672 // Steps (1) and (2):
8673 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8674 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8676 // Check that Alice's commitment transaction now contains an output for this HTLC.
8677 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8678 check_spends!(alice_txn[0], chan_ab.3);
8679 assert_eq!(alice_txn[0].output.len(), 2);
8680 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8681 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8682 assert_eq!(alice_txn.len(), 2);
8684 // Steps (3) and (4):
8685 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8686 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8687 let mut force_closing_node = 0; // Alice force-closes
8688 let mut counterparty_node = 1; // Bob if Alice force-closes
8691 if !broadcast_alice {
8692 force_closing_node = 1;
8693 counterparty_node = 0;
8695 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8696 check_closed_broadcast!(nodes[force_closing_node], true);
8697 check_added_monitors!(nodes[force_closing_node], 1);
8698 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8699 if go_onchain_before_fulfill {
8700 let txn_to_broadcast = match broadcast_alice {
8701 true => alice_txn.clone(),
8702 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8704 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8705 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8706 if broadcast_alice {
8707 check_closed_broadcast!(nodes[1], true);
8708 check_added_monitors!(nodes[1], 1);
8709 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8714 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8715 // process of removing the HTLC from their commitment transactions.
8716 nodes[2].node.claim_funds(payment_preimage);
8717 check_added_monitors!(nodes[2], 1);
8718 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8720 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8721 assert!(carol_updates.update_add_htlcs.is_empty());
8722 assert!(carol_updates.update_fail_htlcs.is_empty());
8723 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8724 assert!(carol_updates.update_fee.is_none());
8725 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8727 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8728 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8729 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8730 if !go_onchain_before_fulfill && broadcast_alice {
8731 let events = nodes[1].node.get_and_clear_pending_msg_events();
8732 assert_eq!(events.len(), 1);
8734 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8735 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8737 _ => panic!("Unexpected event"),
8740 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8741 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8742 // Carol<->Bob's updated commitment transaction info.
8743 check_added_monitors!(nodes[1], 2);
8745 let events = nodes[1].node.get_and_clear_pending_msg_events();
8746 assert_eq!(events.len(), 2);
8747 let bob_revocation = match events[0] {
8748 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8749 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8752 _ => panic!("Unexpected event"),
8754 let bob_updates = match events[1] {
8755 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8756 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8759 _ => panic!("Unexpected event"),
8762 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8763 check_added_monitors!(nodes[2], 1);
8764 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8765 check_added_monitors!(nodes[2], 1);
8767 let events = nodes[2].node.get_and_clear_pending_msg_events();
8768 assert_eq!(events.len(), 1);
8769 let carol_revocation = match events[0] {
8770 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8771 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8774 _ => panic!("Unexpected event"),
8776 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8777 check_added_monitors!(nodes[1], 1);
8779 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8780 // here's where we put said channel's commitment tx on-chain.
8781 let mut txn_to_broadcast = alice_txn.clone();
8782 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8783 if !go_onchain_before_fulfill {
8784 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8785 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8786 // If Bob was the one to force-close, he will have already passed these checks earlier.
8787 if broadcast_alice {
8788 check_closed_broadcast!(nodes[1], true);
8789 check_added_monitors!(nodes[1], 1);
8790 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8792 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8793 if broadcast_alice {
8794 assert_eq!(bob_txn.len(), 1);
8795 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8797 assert_eq!(bob_txn.len(), 2);
8798 check_spends!(bob_txn[0], chan_ab.3);
8803 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8804 // broadcasted commitment transaction.
8806 let script_weight = match broadcast_alice {
8807 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8808 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8810 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8811 // Bob force-closed and broadcasts the commitment transaction along with a
8812 // HTLC-output-claiming transaction.
8813 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8814 if broadcast_alice {
8815 assert_eq!(bob_txn.len(), 1);
8816 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8817 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8819 assert_eq!(bob_txn.len(), 2);
8820 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8821 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8827 fn test_onchain_htlc_settlement_after_close() {
8828 do_test_onchain_htlc_settlement_after_close(true, true);
8829 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8830 do_test_onchain_htlc_settlement_after_close(true, false);
8831 do_test_onchain_htlc_settlement_after_close(false, false);
8835 fn test_duplicate_temporary_channel_id_from_different_peers() {
8836 // Tests that we can accept two different `OpenChannel` requests with the same
8837 // `temporary_channel_id`, as long as they are from different peers.
8838 let chanmon_cfgs = create_chanmon_cfgs(3);
8839 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8840 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8841 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8843 // Create an first channel channel
8844 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8845 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8847 // Create an second channel
8848 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8849 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8851 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8852 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8853 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8855 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8856 // `temporary_channel_id` as they are from different peers.
8857 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8859 let events = nodes[0].node.get_and_clear_pending_msg_events();
8860 assert_eq!(events.len(), 1);
8862 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8863 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8864 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8866 _ => panic!("Unexpected event"),
8870 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8872 let events = nodes[0].node.get_and_clear_pending_msg_events();
8873 assert_eq!(events.len(), 1);
8875 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8876 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8877 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8879 _ => panic!("Unexpected event"),
8885 fn test_duplicate_chan_id() {
8886 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8887 // already open we reject it and keep the old channel.
8889 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8890 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8891 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8892 // updating logic for the existing channel.
8893 let chanmon_cfgs = create_chanmon_cfgs(2);
8894 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8895 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8896 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8898 // Create an initial channel
8899 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8900 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8901 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8902 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()));
8904 // Try to create a second channel with the same temporary_channel_id as the first and check
8905 // that it is rejected.
8906 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8908 let events = nodes[1].node.get_and_clear_pending_msg_events();
8909 assert_eq!(events.len(), 1);
8911 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8912 // Technically, at this point, nodes[1] would be justified in thinking both the
8913 // first (valid) and second (invalid) channels are closed, given they both have
8914 // the same non-temporary channel_id. However, currently we do not, so we just
8915 // move forward with it.
8916 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8917 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8919 _ => panic!("Unexpected event"),
8923 // Move the first channel through the funding flow...
8924 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8926 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8927 check_added_monitors!(nodes[0], 0);
8929 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8930 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8932 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8933 assert_eq!(added_monitors.len(), 1);
8934 assert_eq!(added_monitors[0].0, funding_output);
8935 added_monitors.clear();
8937 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8939 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8941 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8942 let channel_id = funding_outpoint.to_channel_id();
8944 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8947 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8948 // Technically this is allowed by the spec, but we don't support it and there's little reason
8949 // to. Still, it shouldn't cause any other issues.
8950 open_chan_msg.temporary_channel_id = channel_id;
8951 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8953 let events = nodes[1].node.get_and_clear_pending_msg_events();
8954 assert_eq!(events.len(), 1);
8956 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8957 // Technically, at this point, nodes[1] would be justified in thinking both
8958 // channels are closed, but currently we do not, so we just move forward with it.
8959 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8960 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8962 _ => panic!("Unexpected event"),
8966 // Now try to create a second channel which has a duplicate funding output.
8967 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8968 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8969 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8970 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()));
8971 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8973 let funding_created = {
8974 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8975 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8976 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8977 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8978 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8979 // channelmanager in a possibly nonsense state instead).
8980 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8981 let logger = test_utils::TestLogger::new();
8982 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8984 check_added_monitors!(nodes[0], 0);
8985 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8986 // At this point we'll look up if the channel_id is present and immediately fail the channel
8987 // without trying to persist the `ChannelMonitor`.
8988 check_added_monitors!(nodes[1], 0);
8990 // ...still, nodes[1] will reject the duplicate channel.
8992 let events = nodes[1].node.get_and_clear_pending_msg_events();
8993 assert_eq!(events.len(), 1);
8995 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8996 // Technically, at this point, nodes[1] would be justified in thinking both
8997 // channels are closed, but currently we do not, so we just move forward with it.
8998 assert_eq!(msg.channel_id, channel_id);
8999 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9001 _ => panic!("Unexpected event"),
9005 // finally, finish creating the original channel and send a payment over it to make sure
9006 // everything is functional.
9007 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9009 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9010 assert_eq!(added_monitors.len(), 1);
9011 assert_eq!(added_monitors[0].0, funding_output);
9012 added_monitors.clear();
9014 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9016 let events_4 = nodes[0].node.get_and_clear_pending_events();
9017 assert_eq!(events_4.len(), 0);
9018 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9019 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9021 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9022 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9023 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9025 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9029 fn test_error_chans_closed() {
9030 // Test that we properly handle error messages, closing appropriate channels.
9032 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9033 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9034 // we can test various edge cases around it to ensure we don't regress.
9035 let chanmon_cfgs = create_chanmon_cfgs(3);
9036 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9037 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9038 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9040 // Create some initial channels
9041 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9042 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9043 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9045 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9046 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9047 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9049 // Closing a channel from a different peer has no effect
9050 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9051 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9053 // Closing one channel doesn't impact others
9054 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9055 check_added_monitors!(nodes[0], 1);
9056 check_closed_broadcast!(nodes[0], false);
9057 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9058 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9059 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9060 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);
9061 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);
9063 // A null channel ID should close all channels
9064 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9065 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9066 check_added_monitors!(nodes[0], 2);
9067 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9068 let events = nodes[0].node.get_and_clear_pending_msg_events();
9069 assert_eq!(events.len(), 2);
9071 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9072 assert_eq!(msg.contents.flags & 2, 2);
9074 _ => panic!("Unexpected event"),
9077 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9078 assert_eq!(msg.contents.flags & 2, 2);
9080 _ => panic!("Unexpected event"),
9082 // Note that at this point users of a standard PeerHandler will end up calling
9083 // peer_disconnected.
9084 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9085 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9087 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9088 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9089 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9093 fn test_invalid_funding_tx() {
9094 // Test that we properly handle invalid funding transactions sent to us from a peer.
9096 // Previously, all other major lightning implementations had failed to properly sanitize
9097 // funding transactions from their counterparties, leading to a multi-implementation critical
9098 // security vulnerability (though we always sanitized properly, we've previously had
9099 // un-released crashes in the sanitization process).
9101 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9102 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9103 // gave up on it. We test this here by generating such a transaction.
9104 let chanmon_cfgs = create_chanmon_cfgs(2);
9105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9107 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9109 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9110 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()));
9111 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()));
9113 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9115 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9116 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9117 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9119 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9120 let wit_program_script: Script = wit_program.into();
9121 for output in tx.output.iter_mut() {
9122 // Make the confirmed funding transaction have a bogus script_pubkey
9123 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9126 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9127 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()));
9128 check_added_monitors!(nodes[1], 1);
9129 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9131 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()));
9132 check_added_monitors!(nodes[0], 1);
9133 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9135 let events_1 = nodes[0].node.get_and_clear_pending_events();
9136 assert_eq!(events_1.len(), 0);
9138 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9139 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9140 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9142 let expected_err = "funding tx had wrong script/value or output index";
9143 confirm_transaction_at(&nodes[1], &tx, 1);
9144 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9145 check_added_monitors!(nodes[1], 1);
9146 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9147 assert_eq!(events_2.len(), 1);
9148 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9149 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9150 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9151 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9152 } else { panic!(); }
9153 } else { panic!(); }
9154 assert_eq!(nodes[1].node.list_channels().len(), 0);
9156 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9157 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9158 // as its not 32 bytes long.
9159 let mut spend_tx = Transaction {
9160 version: 2i32, lock_time: PackedLockTime::ZERO,
9161 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9162 previous_output: BitcoinOutPoint {
9166 script_sig: Script::new(),
9167 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9168 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9170 output: vec![TxOut {
9172 script_pubkey: Script::new(),
9175 check_spends!(spend_tx, tx);
9176 mine_transaction(&nodes[1], &spend_tx);
9179 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9180 // In the first version of the chain::Confirm interface, after a refactor was made to not
9181 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9182 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9183 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9184 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9185 // spending transaction until height N+1 (or greater). This was due to the way
9186 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9187 // spending transaction at the height the input transaction was confirmed at, not whether we
9188 // should broadcast a spending transaction at the current height.
9189 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9190 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9191 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9192 // until we learned about an additional block.
9194 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9195 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9196 let chanmon_cfgs = create_chanmon_cfgs(3);
9197 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9198 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9199 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9200 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9202 create_announced_chan_between_nodes(&nodes, 0, 1);
9203 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9204 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9205 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9206 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9208 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9209 check_closed_broadcast!(nodes[1], true);
9210 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9211 check_added_monitors!(nodes[1], 1);
9212 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9213 assert_eq!(node_txn.len(), 1);
9215 let conf_height = nodes[1].best_block_info().1;
9216 if !test_height_before_timelock {
9217 connect_blocks(&nodes[1], 24 * 6);
9219 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9220 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9221 if test_height_before_timelock {
9222 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9223 // generate any events or broadcast any transactions
9224 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9225 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9227 // We should broadcast an HTLC transaction spending our funding transaction first
9228 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9229 assert_eq!(spending_txn.len(), 2);
9230 assert_eq!(spending_txn[0], node_txn[0]);
9231 check_spends!(spending_txn[1], node_txn[0]);
9232 // We should also generate a SpendableOutputs event with the to_self output (as its
9234 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9235 assert_eq!(descriptor_spend_txn.len(), 1);
9237 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9238 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9239 // additional block built on top of the current chain.
9240 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9241 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9242 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 }]);
9243 check_added_monitors!(nodes[1], 1);
9245 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9246 assert!(updates.update_add_htlcs.is_empty());
9247 assert!(updates.update_fulfill_htlcs.is_empty());
9248 assert_eq!(updates.update_fail_htlcs.len(), 1);
9249 assert!(updates.update_fail_malformed_htlcs.is_empty());
9250 assert!(updates.update_fee.is_none());
9251 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9252 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9253 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9258 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9259 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9260 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9263 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9264 let chanmon_cfgs = create_chanmon_cfgs(2);
9265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9269 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9271 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9272 .with_features(nodes[1].node.invoice_features());
9273 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9275 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9278 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9279 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9280 check_added_monitors!(nodes[0], 1);
9281 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9282 assert_eq!(events.len(), 1);
9283 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9284 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9285 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9287 expect_pending_htlcs_forwardable!(nodes[1]);
9288 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9291 // Note that we use a different PaymentId here to allow us to duplicativly pay
9292 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9293 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9294 check_added_monitors!(nodes[0], 1);
9295 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9296 assert_eq!(events.len(), 1);
9297 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9298 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9299 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9300 // At this point, nodes[1] would notice it has too much value for the payment. It will
9301 // assume the second is a privacy attack (no longer particularly relevant
9302 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9303 // the first HTLC delivered above.
9306 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9307 nodes[1].node.process_pending_htlc_forwards();
9309 if test_for_second_fail_panic {
9310 // Now we go fail back the first HTLC from the user end.
9311 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9313 let expected_destinations = vec![
9314 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9315 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9317 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9318 nodes[1].node.process_pending_htlc_forwards();
9320 check_added_monitors!(nodes[1], 1);
9321 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9322 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9324 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9325 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9326 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9328 let failure_events = nodes[0].node.get_and_clear_pending_events();
9329 assert_eq!(failure_events.len(), 4);
9330 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9331 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9332 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9333 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9335 // Let the second HTLC fail and claim the first
9336 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9337 nodes[1].node.process_pending_htlc_forwards();
9339 check_added_monitors!(nodes[1], 1);
9340 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9341 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9342 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9344 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9346 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9351 fn test_dup_htlc_second_fail_panic() {
9352 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9353 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9354 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9355 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9356 do_test_dup_htlc_second_rejected(true);
9360 fn test_dup_htlc_second_rejected() {
9361 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9362 // simply reject the second HTLC but are still able to claim the first HTLC.
9363 do_test_dup_htlc_second_rejected(false);
9367 fn test_inconsistent_mpp_params() {
9368 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9369 // such HTLC and allow the second to stay.
9370 let chanmon_cfgs = create_chanmon_cfgs(4);
9371 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9372 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9373 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9375 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9376 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9377 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9378 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9380 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9381 .with_features(nodes[3].node.invoice_features());
9382 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9383 assert_eq!(route.paths.len(), 2);
9384 route.paths.sort_by(|path_a, _| {
9385 // Sort the path so that the path through nodes[1] comes first
9386 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9387 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9390 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9392 let cur_height = nodes[0].best_block_info().1;
9393 let payment_id = PaymentId([42; 32]);
9395 let session_privs = {
9396 // We create a fake route here so that we start with three pending HTLCs, which we'll
9397 // ultimately have, just not right away.
9398 let mut dup_route = route.clone();
9399 dup_route.paths.push(route.paths[1].clone());
9400 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9401 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9403 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9404 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9405 &None, session_privs[0]).unwrap();
9406 check_added_monitors!(nodes[0], 1);
9409 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9410 assert_eq!(events.len(), 1);
9411 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9413 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9415 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9416 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9417 check_added_monitors!(nodes[0], 1);
9420 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9421 assert_eq!(events.len(), 1);
9422 let payment_event = SendEvent::from_event(events.pop().unwrap());
9424 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9425 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9427 expect_pending_htlcs_forwardable!(nodes[2]);
9428 check_added_monitors!(nodes[2], 1);
9430 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9431 assert_eq!(events.len(), 1);
9432 let payment_event = SendEvent::from_event(events.pop().unwrap());
9434 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9435 check_added_monitors!(nodes[3], 0);
9436 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9438 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9439 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9440 // post-payment_secrets) and fail back the new HTLC.
9442 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9443 nodes[3].node.process_pending_htlc_forwards();
9444 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9445 nodes[3].node.process_pending_htlc_forwards();
9447 check_added_monitors!(nodes[3], 1);
9449 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9450 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9451 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9453 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 }]);
9454 check_added_monitors!(nodes[2], 1);
9456 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9457 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9458 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9460 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9462 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9463 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9464 &None, session_privs[2]).unwrap();
9465 check_added_monitors!(nodes[0], 1);
9467 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9468 assert_eq!(events.len(), 1);
9469 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9471 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9472 let events = nodes[0].node.get_and_clear_pending_events();
9473 assert_eq!(events.len(), 3);
9475 Event::PaymentSent { payment_hash, .. } => { // The payment was abandoned earlier, so the fee paid will be None
9476 assert_eq!(payment_hash, our_payment_hash);
9478 _ => panic!("Unexpected event")
9481 Event::PaymentPathSuccessful { payment_hash, .. } => {
9482 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9484 _ => panic!("Unexpected event")
9487 Event::PaymentPathSuccessful { payment_hash, .. } => {
9488 assert_eq!(payment_hash.unwrap(), our_payment_hash);
9490 _ => panic!("Unexpected event")
9495 fn test_keysend_payments_to_public_node() {
9496 let chanmon_cfgs = create_chanmon_cfgs(2);
9497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9501 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9502 let network_graph = nodes[0].network_graph.clone();
9503 let payer_pubkey = nodes[0].node.get_our_node_id();
9504 let payee_pubkey = nodes[1].node.get_our_node_id();
9505 let route_params = RouteParameters {
9506 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9507 final_value_msat: 10000,
9509 let scorer = test_utils::TestScorer::new();
9510 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9511 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9513 let test_preimage = PaymentPreimage([42; 32]);
9514 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9515 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9516 check_added_monitors!(nodes[0], 1);
9517 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9518 assert_eq!(events.len(), 1);
9519 let event = events.pop().unwrap();
9520 let path = vec![&nodes[1]];
9521 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9522 claim_payment(&nodes[0], &path, test_preimage);
9526 fn test_keysend_payments_to_private_node() {
9527 let chanmon_cfgs = create_chanmon_cfgs(2);
9528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9532 let payer_pubkey = nodes[0].node.get_our_node_id();
9533 let payee_pubkey = nodes[1].node.get_our_node_id();
9535 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9536 let route_params = RouteParameters {
9537 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9538 final_value_msat: 10000,
9540 let network_graph = nodes[0].network_graph.clone();
9541 let first_hops = nodes[0].node.list_usable_channels();
9542 let scorer = test_utils::TestScorer::new();
9543 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9544 let route = find_route(
9545 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9546 nodes[0].logger, &scorer, &random_seed_bytes
9549 let test_preimage = PaymentPreimage([42; 32]);
9550 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9551 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9552 check_added_monitors!(nodes[0], 1);
9553 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9554 assert_eq!(events.len(), 1);
9555 let event = events.pop().unwrap();
9556 let path = vec![&nodes[1]];
9557 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9558 claim_payment(&nodes[0], &path, test_preimage);
9562 fn test_double_partial_claim() {
9563 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9564 // time out, the sender resends only some of the MPP parts, then the user processes the
9565 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9567 let chanmon_cfgs = create_chanmon_cfgs(4);
9568 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9569 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9570 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9572 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9573 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9574 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9575 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9577 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9578 assert_eq!(route.paths.len(), 2);
9579 route.paths.sort_by(|path_a, _| {
9580 // Sort the path so that the path through nodes[1] comes first
9581 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9582 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9585 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9586 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9587 // amount of time to respond to.
9589 // Connect some blocks to time out the payment
9590 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9591 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9593 let failed_destinations = vec![
9594 HTLCDestination::FailedPayment { payment_hash },
9595 HTLCDestination::FailedPayment { payment_hash },
9597 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9599 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9601 // nodes[1] now retries one of the two paths...
9602 nodes[0].node.send_payment_with_route(&route, payment_hash,
9603 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9604 check_added_monitors!(nodes[0], 2);
9606 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9607 assert_eq!(events.len(), 2);
9608 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9609 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9611 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9612 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9613 nodes[3].node.claim_funds(payment_preimage);
9614 check_added_monitors!(nodes[3], 0);
9615 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9618 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9619 #[derive(Clone, Copy, PartialEq)]
9620 enum ExposureEvent {
9621 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9623 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9625 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9626 AtUpdateFeeOutbound,
9629 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9630 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9633 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9634 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9635 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9636 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9637 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9638 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9639 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9640 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9642 let chanmon_cfgs = create_chanmon_cfgs(2);
9643 let mut config = test_default_channel_config();
9644 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9647 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9649 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9650 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9651 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9652 open_channel.max_accepted_htlcs = 60;
9654 open_channel.dust_limit_satoshis = 546;
9656 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9657 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9658 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9660 let opt_anchors = false;
9662 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9665 let mut node_0_per_peer_lock;
9666 let mut node_0_peer_state_lock;
9667 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9668 chan.holder_dust_limit_satoshis = 546;
9671 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9672 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()));
9673 check_added_monitors!(nodes[1], 1);
9674 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9676 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()));
9677 check_added_monitors!(nodes[0], 1);
9678 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9680 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9681 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9682 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9684 let dust_buffer_feerate = {
9685 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9686 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9687 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9688 chan.get_dust_buffer_feerate(None) as u64
9690 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;
9691 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9693 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;
9694 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9696 let dust_htlc_on_counterparty_tx: u64 = 25;
9697 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9700 if dust_outbound_balance {
9701 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9702 // Outbound dust balance: 4372 sats
9703 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9704 for _ in 0..dust_outbound_htlc_on_holder_tx {
9705 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9706 nodes[0].node.send_payment_with_route(&route, payment_hash,
9707 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9710 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9711 // Inbound dust balance: 4372 sats
9712 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9713 for _ in 0..dust_inbound_htlc_on_holder_tx {
9714 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9718 if dust_outbound_balance {
9719 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9720 // Outbound dust balance: 5000 sats
9721 for _ in 0..dust_htlc_on_counterparty_tx {
9722 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9723 nodes[0].node.send_payment_with_route(&route, payment_hash,
9724 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9727 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9728 // Inbound dust balance: 5000 sats
9729 for _ in 0..dust_htlc_on_counterparty_tx {
9730 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9735 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9736 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9737 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 });
9738 let mut config = UserConfig::default();
9739 // With default dust exposure: 5000 sats
9741 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9742 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9743 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9744 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9745 ), true, APIError::ChannelUnavailable { ref err },
9746 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)));
9748 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9749 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9750 ), true, APIError::ChannelUnavailable { ref err },
9751 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)));
9753 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9754 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 });
9755 nodes[1].node.send_payment_with_route(&route, payment_hash,
9756 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9757 check_added_monitors!(nodes[1], 1);
9758 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9759 assert_eq!(events.len(), 1);
9760 let payment_event = SendEvent::from_event(events.remove(0));
9761 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9762 // With default dust exposure: 5000 sats
9764 // Outbound dust balance: 6399 sats
9765 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9766 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9767 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);
9769 // Outbound dust balance: 5200 sats
9770 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);
9772 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9773 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9774 nodes[0].node.send_payment_with_route(&route, payment_hash,
9775 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9777 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9778 *feerate_lock = *feerate_lock * 10;
9780 nodes[0].node.timer_tick_occurred();
9781 check_added_monitors!(nodes[0], 1);
9782 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9785 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9786 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9787 added_monitors.clear();
9791 fn test_max_dust_htlc_exposure() {
9792 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9793 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9794 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9795 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9796 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9797 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9798 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9799 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9800 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9801 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9802 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9803 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9807 fn test_non_final_funding_tx() {
9808 let chanmon_cfgs = create_chanmon_cfgs(2);
9809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9811 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9813 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9814 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9815 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9816 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9817 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9819 let best_height = nodes[0].node.best_block.read().unwrap().height();
9821 let chan_id = *nodes[0].network_chan_count.borrow();
9822 let events = nodes[0].node.get_and_clear_pending_events();
9823 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9824 assert_eq!(events.len(), 1);
9825 let mut tx = match events[0] {
9826 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9827 // Timelock the transaction _beyond_ the best client height + 2.
9828 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9829 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9832 _ => panic!("Unexpected event"),
9834 // Transaction should fail as it's evaluated as non-final for propagation.
9835 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9836 Err(APIError::APIMisuseError { err }) => {
9837 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9842 // However, transaction should be accepted if it's in a +2 headroom from best block.
9843 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9844 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9845 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9849 fn accept_busted_but_better_fee() {
9850 // If a peer sends us a fee update that is too low, but higher than our previous channel
9851 // feerate, we should accept it. In the future we may want to consider closing the channel
9852 // later, but for now we only accept the update.
9853 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9854 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9855 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9856 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9858 create_chan_between_nodes(&nodes[0], &nodes[1]);
9860 // Set nodes[1] to expect 5,000 sat/kW.
9862 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9863 *feerate_lock = 5000;
9866 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9868 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9869 *feerate_lock = 1000;
9871 nodes[0].node.timer_tick_occurred();
9872 check_added_monitors!(nodes[0], 1);
9874 let events = nodes[0].node.get_and_clear_pending_msg_events();
9875 assert_eq!(events.len(), 1);
9877 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9878 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9879 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9881 _ => panic!("Unexpected event"),
9884 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9888 *feerate_lock = 2000;
9890 nodes[0].node.timer_tick_occurred();
9891 check_added_monitors!(nodes[0], 1);
9893 let events = nodes[0].node.get_and_clear_pending_msg_events();
9894 assert_eq!(events.len(), 1);
9896 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9897 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9898 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9900 _ => panic!("Unexpected event"),
9903 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9906 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9907 *feerate_lock = 1000;
9909 nodes[0].node.timer_tick_occurred();
9910 check_added_monitors!(nodes[0], 1);
9912 let events = nodes[0].node.get_and_clear_pending_msg_events();
9913 assert_eq!(events.len(), 1);
9915 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9916 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9917 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9918 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9919 check_closed_broadcast!(nodes[1], true);
9920 check_added_monitors!(nodes[1], 1);
9922 _ => panic!("Unexpected event"),
9926 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9927 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9928 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9929 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9930 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9931 let min_final_cltv_expiry_delta = 120;
9932 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9933 min_final_cltv_expiry_delta - 2 };
9934 let recv_value = 100_000;
9936 create_chan_between_nodes(&nodes[0], &nodes[1]);
9938 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9939 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9940 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9941 Some(recv_value), Some(min_final_cltv_expiry_delta));
9942 (payment_hash, payment_preimage, payment_secret)
9944 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9945 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9947 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9948 nodes[0].node.send_payment_with_route(&route, payment_hash,
9949 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9950 check_added_monitors!(nodes[0], 1);
9951 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9952 assert_eq!(events.len(), 1);
9953 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9954 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9955 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9956 expect_pending_htlcs_forwardable!(nodes[1]);
9959 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9960 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9962 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9964 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9966 check_added_monitors!(nodes[1], 1);
9968 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9969 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9970 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9972 expect_payment_failed!(nodes[0], payment_hash, true);
9977 fn test_payment_with_custom_min_cltv_expiry_delta() {
9978 do_payment_with_custom_min_final_cltv_expiry(false, false);
9979 do_payment_with_custom_min_final_cltv_expiry(false, true);
9980 do_payment_with_custom_min_final_cltv_expiry(true, false);
9981 do_payment_with_custom_min_final_cltv_expiry(true, true);