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, PaymentFailureReason};
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,
745 partial_signature_with_nonce: None,
748 let update_fee = msgs::UpdateFee {
750 feerate_per_kw: non_buffer_feerate + 4,
753 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
755 //While producing the commitment_signed response after handling a received update_fee request the
756 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
757 //Should produce and error.
758 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
759 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
760 check_added_monitors!(nodes[1], 1);
761 check_closed_broadcast!(nodes[1], true);
762 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
766 fn test_update_fee_with_fundee_update_add_htlc() {
767 let chanmon_cfgs = create_chanmon_cfgs(2);
768 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
769 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
770 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
771 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
774 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
777 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
780 nodes[0].node.timer_tick_occurred();
781 check_added_monitors!(nodes[0], 1);
783 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
784 assert_eq!(events_0.len(), 1);
785 let (update_msg, commitment_signed) = match events_0[0] {
786 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 } } => {
787 (update_fee.as_ref(), commitment_signed)
789 _ => panic!("Unexpected event"),
791 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
792 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
793 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
794 check_added_monitors!(nodes[1], 1);
796 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
798 // nothing happens since node[1] is in AwaitingRemoteRevoke
799 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
800 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
802 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
803 assert_eq!(added_monitors.len(), 0);
804 added_monitors.clear();
806 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 // node[1] has nothing to do
810 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
811 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
812 check_added_monitors!(nodes[0], 1);
814 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
815 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
816 // No commitment_signed so get_event_msg's assert(len == 1) passes
817 check_added_monitors!(nodes[0], 1);
818 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
819 check_added_monitors!(nodes[1], 1);
820 // AwaitingRemoteRevoke ends here
822 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
823 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
824 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
825 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
826 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
827 assert_eq!(commitment_update.update_fee.is_none(), true);
829 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
830 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
831 check_added_monitors!(nodes[0], 1);
832 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
834 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
835 check_added_monitors!(nodes[1], 1);
836 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
838 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
839 check_added_monitors!(nodes[1], 1);
840 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
841 // No commitment_signed so get_event_msg's assert(len == 1) passes
843 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
844 check_added_monitors!(nodes[0], 1);
845 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
847 expect_pending_htlcs_forwardable!(nodes[0]);
849 let events = nodes[0].node.get_and_clear_pending_events();
850 assert_eq!(events.len(), 1);
852 Event::PaymentClaimable { .. } => { },
853 _ => panic!("Unexpected event"),
856 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
858 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
859 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
860 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
861 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
862 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
866 fn test_update_fee() {
867 let chanmon_cfgs = create_chanmon_cfgs(2);
868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
870 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
871 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
872 let channel_id = chan.2;
875 // (1) update_fee/commitment_signed ->
876 // <- (2) revoke_and_ack
877 // .- send (3) commitment_signed
878 // (4) update_fee/commitment_signed ->
879 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
880 // <- (3) commitment_signed delivered
881 // send (6) revoke_and_ack -.
882 // <- (5) deliver revoke_and_ack
883 // (6) deliver revoke_and_ack ->
884 // .- send (7) commitment_signed in response to (4)
885 // <- (7) deliver commitment_signed
888 // Create and deliver (1)...
891 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
892 feerate = *feerate_lock;
893 *feerate_lock = feerate + 20;
895 nodes[0].node.timer_tick_occurred();
896 check_added_monitors!(nodes[0], 1);
898 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
899 assert_eq!(events_0.len(), 1);
900 let (update_msg, commitment_signed) = match events_0[0] {
901 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 } } => {
902 (update_fee.as_ref(), commitment_signed)
904 _ => panic!("Unexpected event"),
906 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
908 // Generate (2) and (3):
909 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
910 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
911 check_added_monitors!(nodes[1], 1);
914 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
915 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
916 check_added_monitors!(nodes[0], 1);
918 // Create and deliver (4)...
920 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
921 *feerate_lock = feerate + 30;
923 nodes[0].node.timer_tick_occurred();
924 check_added_monitors!(nodes[0], 1);
925 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
926 assert_eq!(events_0.len(), 1);
927 let (update_msg, commitment_signed) = match events_0[0] {
928 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 } } => {
929 (update_fee.as_ref(), commitment_signed)
931 _ => panic!("Unexpected event"),
934 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
935 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
936 check_added_monitors!(nodes[1], 1);
938 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
939 // No commitment_signed so get_event_msg's assert(len == 1) passes
941 // Handle (3), creating (6):
942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
943 check_added_monitors!(nodes[0], 1);
944 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
945 // No commitment_signed so get_event_msg's assert(len == 1) passes
948 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
949 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
950 check_added_monitors!(nodes[0], 1);
952 // Deliver (6), creating (7):
953 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
954 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
955 assert!(commitment_update.update_add_htlcs.is_empty());
956 assert!(commitment_update.update_fulfill_htlcs.is_empty());
957 assert!(commitment_update.update_fail_htlcs.is_empty());
958 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
959 assert!(commitment_update.update_fee.is_none());
960 check_added_monitors!(nodes[1], 1);
963 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
964 check_added_monitors!(nodes[0], 1);
965 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
966 // No commitment_signed so get_event_msg's assert(len == 1) passes
968 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
969 check_added_monitors!(nodes[1], 1);
970 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
972 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
973 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
974 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
975 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
976 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
980 fn fake_network_test() {
981 // Simple test which builds a network of ChannelManagers, connects them to each other, and
982 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
983 let chanmon_cfgs = create_chanmon_cfgs(4);
984 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
985 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
986 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
988 // Create some initial channels
989 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
990 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
991 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
993 // Rebalance the network a bit by relaying one payment through all the channels...
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);
996 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
997 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
999 // Send some more payments
1000 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1001 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1002 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1004 // Test failure packets
1005 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1006 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1008 // Add a new channel that skips 3
1009 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1011 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1012 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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);
1016 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1017 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019 // Do some rebalance loop payments, simultaneously
1020 let mut hops = Vec::with_capacity(3);
1021 hops.push(RouteHop {
1022 pubkey: nodes[2].node.get_our_node_id(),
1023 node_features: NodeFeatures::empty(),
1024 short_channel_id: chan_2.0.contents.short_channel_id,
1025 channel_features: ChannelFeatures::empty(),
1027 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1029 hops.push(RouteHop {
1030 pubkey: nodes[3].node.get_our_node_id(),
1031 node_features: NodeFeatures::empty(),
1032 short_channel_id: chan_3.0.contents.short_channel_id,
1033 channel_features: ChannelFeatures::empty(),
1035 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1037 hops.push(RouteHop {
1038 pubkey: nodes[1].node.get_our_node_id(),
1039 node_features: nodes[1].node.node_features(),
1040 short_channel_id: chan_4.0.contents.short_channel_id,
1041 channel_features: nodes[1].node.channel_features(),
1043 cltv_expiry_delta: TEST_FINAL_CLTV,
1045 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;
1046 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;
1047 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;
1049 let mut hops = Vec::with_capacity(3);
1050 hops.push(RouteHop {
1051 pubkey: nodes[3].node.get_our_node_id(),
1052 node_features: NodeFeatures::empty(),
1053 short_channel_id: chan_4.0.contents.short_channel_id,
1054 channel_features: ChannelFeatures::empty(),
1056 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1058 hops.push(RouteHop {
1059 pubkey: nodes[2].node.get_our_node_id(),
1060 node_features: NodeFeatures::empty(),
1061 short_channel_id: chan_3.0.contents.short_channel_id,
1062 channel_features: ChannelFeatures::empty(),
1064 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1066 hops.push(RouteHop {
1067 pubkey: nodes[1].node.get_our_node_id(),
1068 node_features: nodes[1].node.node_features(),
1069 short_channel_id: chan_2.0.contents.short_channel_id,
1070 channel_features: nodes[1].node.channel_features(),
1072 cltv_expiry_delta: TEST_FINAL_CLTV,
1074 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;
1075 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;
1076 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;
1078 // Claim the rebalances...
1079 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1080 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1082 // Close down the channels...
1083 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1084 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1085 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1086 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1087 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1089 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1090 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1092 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1093 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1094 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1098 fn holding_cell_htlc_counting() {
1099 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1100 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1101 // commitment dance rounds.
1102 let chanmon_cfgs = create_chanmon_cfgs(3);
1103 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1104 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1105 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1106 create_announced_chan_between_nodes(&nodes, 0, 1);
1107 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1109 let mut payments = Vec::new();
1111 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1112 nodes[1].node.send_payment_with_route(&route, payment_hash,
1113 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1114 payments.push((payment_preimage, payment_hash));
1116 check_added_monitors!(nodes[1], 1);
1118 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1119 assert_eq!(events.len(), 1);
1120 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1121 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1123 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1124 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1126 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1128 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1129 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1130 ), true, APIError::ChannelUnavailable { ref err },
1131 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1132 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1133 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1136 // This should also be true if we try to forward a payment.
1137 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1139 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1140 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1141 check_added_monitors!(nodes[0], 1);
1144 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1145 assert_eq!(events.len(), 1);
1146 let payment_event = SendEvent::from_event(events.pop().unwrap());
1147 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1149 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1150 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1151 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1152 // fails), the second will process the resulting failure and fail the HTLC backward.
1153 expect_pending_htlcs_forwardable!(nodes[1]);
1154 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 }]);
1155 check_added_monitors!(nodes[1], 1);
1157 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1158 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1159 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1161 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1163 // Now forward all the pending HTLCs and claim them back
1164 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1165 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1166 check_added_monitors!(nodes[2], 1);
1168 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1169 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1173 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1174 check_added_monitors!(nodes[1], 1);
1175 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1177 for ref update in as_updates.update_add_htlcs.iter() {
1178 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1180 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1181 check_added_monitors!(nodes[2], 1);
1182 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1183 check_added_monitors!(nodes[2], 1);
1184 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1186 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1187 check_added_monitors!(nodes[1], 1);
1188 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1189 check_added_monitors!(nodes[1], 1);
1190 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1192 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1193 check_added_monitors!(nodes[2], 1);
1195 expect_pending_htlcs_forwardable!(nodes[2]);
1197 let events = nodes[2].node.get_and_clear_pending_events();
1198 assert_eq!(events.len(), payments.len());
1199 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1201 &Event::PaymentClaimable { ref payment_hash, .. } => {
1202 assert_eq!(*payment_hash, *hash);
1204 _ => panic!("Unexpected event"),
1208 for (preimage, _) in payments.drain(..) {
1209 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1212 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1216 fn duplicate_htlc_test() {
1217 // Test that we accept duplicate payment_hash HTLCs across the network and that
1218 // claiming/failing them are all separate and don't affect each other
1219 let chanmon_cfgs = create_chanmon_cfgs(6);
1220 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1221 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1222 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1224 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1225 create_announced_chan_between_nodes(&nodes, 0, 3);
1226 create_announced_chan_between_nodes(&nodes, 1, 3);
1227 create_announced_chan_between_nodes(&nodes, 2, 3);
1228 create_announced_chan_between_nodes(&nodes, 3, 4);
1229 create_announced_chan_between_nodes(&nodes, 3, 5);
1231 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1233 *nodes[0].network_payment_count.borrow_mut() -= 1;
1234 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1236 *nodes[0].network_payment_count.borrow_mut() -= 1;
1237 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1239 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1240 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1241 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1245 fn test_duplicate_htlc_different_direction_onchain() {
1246 // Test that ChannelMonitor doesn't generate 2 preimage txn
1247 // when we have 2 HTLCs with same preimage that go across a node
1248 // in opposite directions, even with the same payment secret.
1249 let chanmon_cfgs = create_chanmon_cfgs(2);
1250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1252 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1254 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1257 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1259 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1261 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1262 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1263 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1265 // Provide preimage to node 0 by claiming payment
1266 nodes[0].node.claim_funds(payment_preimage);
1267 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1268 check_added_monitors!(nodes[0], 1);
1270 // Broadcast node 1 commitment txn
1271 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1273 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1274 let mut has_both_htlcs = 0; // check htlcs match ones committed
1275 for outp in remote_txn[0].output.iter() {
1276 if outp.value == 800_000 / 1000 {
1277 has_both_htlcs += 1;
1278 } else if outp.value == 900_000 / 1000 {
1279 has_both_htlcs += 1;
1282 assert_eq!(has_both_htlcs, 2);
1284 mine_transaction(&nodes[0], &remote_txn[0]);
1285 check_added_monitors!(nodes[0], 1);
1286 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1287 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1289 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1290 assert_eq!(claim_txn.len(), 3);
1292 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1293 check_spends!(claim_txn[1], remote_txn[0]);
1294 check_spends!(claim_txn[2], remote_txn[0]);
1295 let preimage_tx = &claim_txn[0];
1296 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1297 (&claim_txn[1], &claim_txn[2])
1299 (&claim_txn[2], &claim_txn[1])
1302 assert_eq!(preimage_tx.input.len(), 1);
1303 assert_eq!(preimage_bump_tx.input.len(), 1);
1305 assert_eq!(preimage_tx.input.len(), 1);
1306 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1307 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1309 assert_eq!(timeout_tx.input.len(), 1);
1310 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1311 check_spends!(timeout_tx, remote_txn[0]);
1312 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1314 let events = nodes[0].node.get_and_clear_pending_msg_events();
1315 assert_eq!(events.len(), 3);
1318 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1319 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1320 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1321 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1323 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, .. } } => {
1324 assert!(update_add_htlcs.is_empty());
1325 assert!(update_fail_htlcs.is_empty());
1326 assert_eq!(update_fulfill_htlcs.len(), 1);
1327 assert!(update_fail_malformed_htlcs.is_empty());
1328 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1330 _ => panic!("Unexpected event"),
1336 fn test_basic_channel_reserve() {
1337 let chanmon_cfgs = create_chanmon_cfgs(2);
1338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1341 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1343 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1344 let channel_reserve = chan_stat.channel_reserve_msat;
1346 // The 2* and +1 are for the fee spike reserve.
1347 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));
1348 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1349 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1350 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1351 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1353 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1355 &APIError::ChannelUnavailable{ref err} =>
1356 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1357 _ => panic!("Unexpected error variant"),
1360 _ => panic!("Unexpected error variant"),
1362 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1363 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1365 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1369 fn test_fee_spike_violation_fails_htlc() {
1370 let chanmon_cfgs = create_chanmon_cfgs(2);
1371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1374 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1376 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1377 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1378 let secp_ctx = Secp256k1::new();
1379 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1381 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1383 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1384 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1385 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1386 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1387 let msg = msgs::UpdateAddHTLC {
1390 amount_msat: htlc_msat,
1391 payment_hash: payment_hash,
1392 cltv_expiry: htlc_cltv,
1393 onion_routing_packet: onion_packet,
1396 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1398 // Now manually create the commitment_signed message corresponding to the update_add
1399 // nodes[0] just sent. In the code for construction of this message, "local" refers
1400 // to the sender of the message, and "remote" refers to the receiver.
1402 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1404 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1406 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1407 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1408 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1409 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1410 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1411 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1412 let chan_signer = local_chan.get_signer();
1413 // Make the signer believe we validated another commitment, so we can release the secret
1414 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1416 let pubkeys = chan_signer.pubkeys();
1417 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1418 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1419 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1420 chan_signer.pubkeys().funding_pubkey)
1422 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1423 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1424 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1425 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1426 let chan_signer = remote_chan.get_signer();
1427 let pubkeys = chan_signer.pubkeys();
1428 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1429 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1430 chan_signer.pubkeys().funding_pubkey)
1433 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1434 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1435 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1437 // Build the remote commitment transaction so we can sign it, and then later use the
1438 // signature for the commitment_signed message.
1439 let local_chan_balance = 1313;
1441 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1443 amount_msat: 3460001,
1444 cltv_expiry: htlc_cltv,
1446 transaction_output_index: Some(1),
1449 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1452 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1453 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1454 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1455 let local_chan_signer = local_chan.get_signer();
1456 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1460 local_chan.opt_anchors(), local_funding, remote_funding,
1461 commit_tx_keys.clone(),
1463 &mut vec![(accepted_htlc_info, ())],
1464 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1466 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1469 let commit_signed_msg = msgs::CommitmentSigned {
1472 htlc_signatures: res.1,
1474 partial_signature_with_nonce: None,
1477 // Send the commitment_signed message to the nodes[1].
1478 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1479 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1481 // Send the RAA to nodes[1].
1482 let raa_msg = msgs::RevokeAndACK {
1484 per_commitment_secret: local_secret,
1485 next_per_commitment_point: next_local_point,
1487 next_local_nonce: None,
1489 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1491 let events = nodes[1].node.get_and_clear_pending_msg_events();
1492 assert_eq!(events.len(), 1);
1493 // Make sure the HTLC failed in the way we expect.
1495 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1496 assert_eq!(update_fail_htlcs.len(), 1);
1497 update_fail_htlcs[0].clone()
1499 _ => panic!("Unexpected event"),
1501 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1502 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1504 check_added_monitors!(nodes[1], 2);
1508 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1509 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1510 // Set the fee rate for the channel very high, to the point where the fundee
1511 // sending any above-dust amount would result in a channel reserve violation.
1512 // In this test we check that we would be prevented from sending an HTLC in
1514 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1517 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1518 let default_config = UserConfig::default();
1519 let opt_anchors = false;
1521 let mut push_amt = 100_000_000;
1522 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1524 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1526 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1528 // Sending exactly enough to hit the reserve amount should be accepted
1529 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1530 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1533 // However one more HTLC should be significantly over the reserve amount and fail.
1534 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1535 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1536 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1537 ), true, APIError::ChannelUnavailable { ref err },
1538 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1539 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1540 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);
1544 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1545 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1546 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1547 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1548 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1549 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1550 let default_config = UserConfig::default();
1551 let opt_anchors = false;
1553 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1554 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1555 // transaction fee with 0 HTLCs (183 sats)).
1556 let mut push_amt = 100_000_000;
1557 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1558 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1559 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1561 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1562 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1566 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1567 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1568 let secp_ctx = Secp256k1::new();
1569 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1570 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1571 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1572 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1573 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1574 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1575 let msg = msgs::UpdateAddHTLC {
1577 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1578 amount_msat: htlc_msat,
1579 payment_hash: payment_hash,
1580 cltv_expiry: htlc_cltv,
1581 onion_routing_packet: onion_packet,
1584 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1585 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1586 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);
1587 assert_eq!(nodes[0].node.list_channels().len(), 0);
1588 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1589 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1590 check_added_monitors!(nodes[0], 1);
1591 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() });
1595 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1596 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1597 // calculating our commitment transaction fee (this was previously broken).
1598 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1599 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1601 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1602 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1603 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1604 let default_config = UserConfig::default();
1605 let opt_anchors = false;
1607 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1608 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1609 // transaction fee with 0 HTLCs (183 sats)).
1610 let mut push_amt = 100_000_000;
1611 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1612 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1613 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1615 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1616 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1617 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1618 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1619 // commitment transaction fee.
1620 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1622 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1623 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1624 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1627 // One more than the dust amt should fail, however.
1628 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1629 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1630 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1631 ), true, APIError::ChannelUnavailable { ref err },
1632 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1636 fn test_chan_init_feerate_unaffordability() {
1637 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1638 // channel reserve and feerate requirements.
1639 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1640 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1643 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1644 let default_config = UserConfig::default();
1645 let opt_anchors = false;
1647 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1649 let mut push_amt = 100_000_000;
1650 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1651 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1652 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1654 // During open, we don't have a "counterparty channel reserve" to check against, so that
1655 // requirement only comes into play on the open_channel handling side.
1656 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1657 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1658 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1659 open_channel_msg.push_msat += 1;
1660 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1662 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1663 assert_eq!(msg_events.len(), 1);
1664 match msg_events[0] {
1665 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1666 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1668 _ => panic!("Unexpected event"),
1673 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1674 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1675 // calculating our counterparty's commitment transaction fee (this was previously broken).
1676 let chanmon_cfgs = create_chanmon_cfgs(2);
1677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1679 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1682 let payment_amt = 46000; // Dust amount
1683 // In the previous code, these first four payments would succeed.
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);
1689 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1697 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1698 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1699 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1703 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1704 let chanmon_cfgs = create_chanmon_cfgs(3);
1705 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1706 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1707 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1708 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1709 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1712 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1713 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1714 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1715 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1717 // Add a 2* and +1 for the fee spike reserve.
1718 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1719 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;
1720 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1722 // Add a pending HTLC.
1723 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1724 let payment_event_1 = {
1725 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1726 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1727 check_added_monitors!(nodes[0], 1);
1729 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1730 assert_eq!(events.len(), 1);
1731 SendEvent::from_event(events.remove(0))
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1735 // Attempt to trigger a channel reserve violation --> payment failure.
1736 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1737 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;
1738 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1739 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1741 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1742 let secp_ctx = Secp256k1::new();
1743 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1744 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1745 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1746 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1747 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1748 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1749 let msg = msgs::UpdateAddHTLC {
1752 amount_msat: htlc_msat + 1,
1753 payment_hash: our_payment_hash_1,
1754 cltv_expiry: htlc_cltv,
1755 onion_routing_packet: onion_packet,
1758 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1759 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1760 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1761 assert_eq!(nodes[1].node.list_channels().len(), 1);
1762 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1763 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1764 check_added_monitors!(nodes[1], 1);
1765 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1769 fn test_inbound_outbound_capacity_is_not_zero() {
1770 let chanmon_cfgs = create_chanmon_cfgs(2);
1771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1773 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1774 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1775 let channels0 = node_chanmgrs[0].list_channels();
1776 let channels1 = node_chanmgrs[1].list_channels();
1777 let default_config = UserConfig::default();
1778 assert_eq!(channels0.len(), 1);
1779 assert_eq!(channels1.len(), 1);
1781 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1782 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1783 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1785 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1786 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1789 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1790 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1794 fn test_channel_reserve_holding_cell_htlcs() {
1795 let chanmon_cfgs = create_chanmon_cfgs(3);
1796 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1797 // When this test was written, the default base fee floated based on the HTLC count.
1798 // It is now fixed, so we simply set the fee to the expected value here.
1799 let mut config = test_default_channel_config();
1800 config.channel_config.forwarding_fee_base_msat = 239;
1801 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1802 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1803 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1804 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1806 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1807 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1809 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1810 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1812 macro_rules! expect_forward {
1814 let mut events = $node.node.get_and_clear_pending_msg_events();
1815 assert_eq!(events.len(), 1);
1816 check_added_monitors!($node, 1);
1817 let payment_event = SendEvent::from_event(events.remove(0));
1822 let feemsat = 239; // set above
1823 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1824 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1825 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1827 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1829 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1831 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1832 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1833 let (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);
1834 route.paths[0].last_mut().unwrap().fee_msat += 1;
1835 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1837 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1838 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1839 ), true, APIError::ChannelUnavailable { ref err },
1840 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)));
1841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1842 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);
1845 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1846 // nodes[0]'s wealth
1848 let amt_msat = recv_value_0 + total_fee_msat;
1849 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1850 // Also, ensure that each payment has enough to be over the dust limit to
1851 // ensure it'll be included in each commit tx fee calculation.
1852 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1853 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1854 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1858 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1859 .with_features(nodes[2].node.invoice_features()).with_max_channel_saturation_power_of_half(0);
1860 let route = get_route!(nodes[0], payment_params, recv_value_0, TEST_FINAL_CLTV).unwrap();
1861 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1862 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1864 let (stat01_, stat11_, stat12_, stat22_) = (
1865 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1866 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1867 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1868 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1871 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1872 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1873 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1874 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1875 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1878 // adding pending output.
1879 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1880 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1881 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1882 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1883 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1884 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1885 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1886 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1887 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1889 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1890 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1891 let amt_msat_1 = recv_value_1 + total_fee_msat;
1893 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);
1894 let payment_event_1 = {
1895 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1896 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1897 check_added_monitors!(nodes[0], 1);
1899 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1900 assert_eq!(events.len(), 1);
1901 SendEvent::from_event(events.remove(0))
1903 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1905 // channel reserve test with htlc pending output > 0
1906 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1908 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1909 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1910 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1911 ), true, APIError::ChannelUnavailable { ref err },
1912 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1913 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1916 // split the rest to test holding cell
1917 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1918 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1919 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1920 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1922 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1923 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);
1926 // now see if they go through on both sides
1927 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);
1928 // but this will stuck in the holding cell
1929 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1930 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1931 check_added_monitors!(nodes[0], 0);
1932 let events = nodes[0].node.get_and_clear_pending_events();
1933 assert_eq!(events.len(), 0);
1935 // test with outbound holding cell amount > 0
1937 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1938 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1939 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1940 ), true, APIError::ChannelUnavailable { ref err },
1941 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1942 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1943 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
1946 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);
1947 // this will also stuck in the holding cell
1948 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1949 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1950 check_added_monitors!(nodes[0], 0);
1951 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1952 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1954 // flush the pending htlc
1955 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1956 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1957 check_added_monitors!(nodes[1], 1);
1959 // the pending htlc should be promoted to committed
1960 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1961 check_added_monitors!(nodes[0], 1);
1962 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1964 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1965 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1966 // No commitment_signed so get_event_msg's assert(len == 1) passes
1967 check_added_monitors!(nodes[0], 1);
1969 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1970 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1971 check_added_monitors!(nodes[1], 1);
1973 expect_pending_htlcs_forwardable!(nodes[1]);
1975 let ref payment_event_11 = expect_forward!(nodes[1]);
1976 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1977 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1979 expect_pending_htlcs_forwardable!(nodes[2]);
1980 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1982 // flush the htlcs in the holding cell
1983 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1984 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1985 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1986 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1987 expect_pending_htlcs_forwardable!(nodes[1]);
1989 let ref payment_event_3 = expect_forward!(nodes[1]);
1990 assert_eq!(payment_event_3.msgs.len(), 2);
1991 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1992 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1994 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1995 expect_pending_htlcs_forwardable!(nodes[2]);
1997 let events = nodes[2].node.get_and_clear_pending_events();
1998 assert_eq!(events.len(), 2);
2000 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2001 assert_eq!(our_payment_hash_21, *payment_hash);
2002 assert_eq!(recv_value_21, amount_msat);
2003 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2004 assert_eq!(via_channel_id, Some(chan_2.2));
2006 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2007 assert!(payment_preimage.is_none());
2008 assert_eq!(our_payment_secret_21, *payment_secret);
2010 _ => panic!("expected PaymentPurpose::InvoicePayment")
2013 _ => panic!("Unexpected event"),
2016 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2017 assert_eq!(our_payment_hash_22, *payment_hash);
2018 assert_eq!(recv_value_22, amount_msat);
2019 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2020 assert_eq!(via_channel_id, Some(chan_2.2));
2022 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2023 assert!(payment_preimage.is_none());
2024 assert_eq!(our_payment_secret_22, *payment_secret);
2026 _ => panic!("expected PaymentPurpose::InvoicePayment")
2029 _ => panic!("Unexpected event"),
2032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2033 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2034 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2036 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2037 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2038 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2040 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2041 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);
2042 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2043 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2044 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2046 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2047 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2051 fn channel_reserve_in_flight_removes() {
2052 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2053 // can send to its counterparty, but due to update ordering, the other side may not yet have
2054 // considered those HTLCs fully removed.
2055 // This tests that we don't count HTLCs which will not be included in the next remote
2056 // commitment transaction towards the reserve value (as it implies no commitment transaction
2057 // will be generated which violates the remote reserve value).
2058 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2060 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2061 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2062 // you only consider the value of the first HTLC, it may not),
2063 // * start routing a third HTLC from A to B,
2064 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2065 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2066 // * deliver the first fulfill from B
2067 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2069 // * deliver A's response CS and RAA.
2070 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2071 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2072 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2073 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2074 let chanmon_cfgs = create_chanmon_cfgs(2);
2075 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2076 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2077 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2078 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2080 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2081 // Route the first two HTLCs.
2082 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2083 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2084 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2086 // Start routing the third HTLC (this is just used to get everyone in the right state).
2087 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2089 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2090 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2091 check_added_monitors!(nodes[0], 1);
2092 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2093 assert_eq!(events.len(), 1);
2094 SendEvent::from_event(events.remove(0))
2097 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2098 // initial fulfill/CS.
2099 nodes[1].node.claim_funds(payment_preimage_1);
2100 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2101 check_added_monitors!(nodes[1], 1);
2102 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2104 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2105 // remove the second HTLC when we send the HTLC back from B to A.
2106 nodes[1].node.claim_funds(payment_preimage_2);
2107 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2108 check_added_monitors!(nodes[1], 1);
2109 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2111 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2112 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2113 check_added_monitors!(nodes[0], 1);
2114 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2115 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2117 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2118 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2119 check_added_monitors!(nodes[1], 1);
2120 // B is already AwaitingRAA, so cant generate a CS here
2121 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2123 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2124 check_added_monitors!(nodes[1], 1);
2125 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2127 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2128 check_added_monitors!(nodes[0], 1);
2129 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2131 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2132 check_added_monitors!(nodes[1], 1);
2133 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2135 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2136 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2137 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2138 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2139 // on-chain as necessary).
2140 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2141 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2142 check_added_monitors!(nodes[0], 1);
2143 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2144 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2146 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2147 check_added_monitors!(nodes[1], 1);
2148 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2150 expect_pending_htlcs_forwardable!(nodes[1]);
2151 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2153 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2154 // resolve the second HTLC from A's point of view.
2155 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2156 check_added_monitors!(nodes[0], 1);
2157 expect_payment_path_successful!(nodes[0]);
2158 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2160 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2161 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2162 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2164 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2165 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2166 check_added_monitors!(nodes[1], 1);
2167 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2168 assert_eq!(events.len(), 1);
2169 SendEvent::from_event(events.remove(0))
2172 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2173 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2174 check_added_monitors!(nodes[0], 1);
2175 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2177 // Now just resolve all the outstanding messages/HTLCs for completeness...
2179 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2180 check_added_monitors!(nodes[1], 1);
2181 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2183 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2184 check_added_monitors!(nodes[1], 1);
2186 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2187 check_added_monitors!(nodes[0], 1);
2188 expect_payment_path_successful!(nodes[0]);
2189 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2191 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2192 check_added_monitors!(nodes[1], 1);
2193 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2195 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2196 check_added_monitors!(nodes[0], 1);
2198 expect_pending_htlcs_forwardable!(nodes[0]);
2199 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2201 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2202 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2206 fn channel_monitor_network_test() {
2207 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2208 // tests that ChannelMonitor is able to recover from various states.
2209 let chanmon_cfgs = create_chanmon_cfgs(5);
2210 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2211 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2212 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2214 // Create some initial channels
2215 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2216 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2217 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2218 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2220 // Make sure all nodes are at the same starting height
2221 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2222 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2223 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2224 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2225 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2227 // Rebalance the network a bit by relaying one payment through all the channels...
2228 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2230 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2231 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2233 // Simple case with no pending HTLCs:
2234 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2235 check_added_monitors!(nodes[1], 1);
2236 check_closed_broadcast!(nodes[1], true);
2238 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2239 assert_eq!(node_txn.len(), 1);
2240 mine_transaction(&nodes[0], &node_txn[0]);
2241 check_added_monitors!(nodes[0], 1);
2242 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2244 check_closed_broadcast!(nodes[0], true);
2245 assert_eq!(nodes[0].node.list_channels().len(), 0);
2246 assert_eq!(nodes[1].node.list_channels().len(), 1);
2247 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2248 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2250 // One pending HTLC is discarded by the force-close:
2251 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2253 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2254 // broadcasted until we reach the timelock time).
2255 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2256 check_closed_broadcast!(nodes[1], true);
2257 check_added_monitors!(nodes[1], 1);
2259 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2260 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2261 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2262 mine_transaction(&nodes[2], &node_txn[0]);
2263 check_added_monitors!(nodes[2], 1);
2264 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2266 check_closed_broadcast!(nodes[2], true);
2267 assert_eq!(nodes[1].node.list_channels().len(), 0);
2268 assert_eq!(nodes[2].node.list_channels().len(), 1);
2269 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2270 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2272 macro_rules! claim_funds {
2273 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2275 $node.node.claim_funds($preimage);
2276 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2277 check_added_monitors!($node, 1);
2279 let events = $node.node.get_and_clear_pending_msg_events();
2280 assert_eq!(events.len(), 1);
2282 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2283 assert!(update_add_htlcs.is_empty());
2284 assert!(update_fail_htlcs.is_empty());
2285 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2287 _ => panic!("Unexpected event"),
2293 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2294 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2295 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2296 check_added_monitors!(nodes[2], 1);
2297 check_closed_broadcast!(nodes[2], true);
2298 let node2_commitment_txid;
2300 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2301 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2302 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2303 node2_commitment_txid = node_txn[0].txid();
2305 // Claim the payment on nodes[3], giving it knowledge of the preimage
2306 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2307 mine_transaction(&nodes[3], &node_txn[0]);
2308 check_added_monitors!(nodes[3], 1);
2309 check_preimage_claim(&nodes[3], &node_txn);
2311 check_closed_broadcast!(nodes[3], true);
2312 assert_eq!(nodes[2].node.list_channels().len(), 0);
2313 assert_eq!(nodes[3].node.list_channels().len(), 1);
2314 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2315 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2317 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2318 // confusing us in the following tests.
2319 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2321 // One pending HTLC to time out:
2322 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2323 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2326 let (close_chan_update_1, close_chan_update_2) = {
2327 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2328 let events = nodes[3].node.get_and_clear_pending_msg_events();
2329 assert_eq!(events.len(), 2);
2330 let close_chan_update_1 = match events[0] {
2331 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2334 _ => panic!("Unexpected event"),
2337 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2338 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2340 _ => panic!("Unexpected event"),
2342 check_added_monitors!(nodes[3], 1);
2344 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2346 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2347 node_txn.retain(|tx| {
2348 if tx.input[0].previous_output.txid == node2_commitment_txid {
2354 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2356 // Claim the payment on nodes[4], giving it knowledge of the preimage
2357 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2359 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2360 let events = nodes[4].node.get_and_clear_pending_msg_events();
2361 assert_eq!(events.len(), 2);
2362 let close_chan_update_2 = match events[0] {
2363 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2366 _ => panic!("Unexpected event"),
2369 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2370 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2372 _ => panic!("Unexpected event"),
2374 check_added_monitors!(nodes[4], 1);
2375 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2377 mine_transaction(&nodes[4], &node_txn[0]);
2378 check_preimage_claim(&nodes[4], &node_txn);
2379 (close_chan_update_1, close_chan_update_2)
2381 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2382 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2383 assert_eq!(nodes[3].node.list_channels().len(), 0);
2384 assert_eq!(nodes[4].node.list_channels().len(), 0);
2386 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2387 ChannelMonitorUpdateStatus::Completed);
2388 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2389 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2393 fn test_justice_tx() {
2394 // Test justice txn built on revoked HTLC-Success tx, against both sides
2395 let mut alice_config = UserConfig::default();
2396 alice_config.channel_handshake_config.announced_channel = true;
2397 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2398 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2399 let mut bob_config = UserConfig::default();
2400 bob_config.channel_handshake_config.announced_channel = true;
2401 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2402 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2403 let user_cfgs = [Some(alice_config), Some(bob_config)];
2404 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2405 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2406 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2407 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2408 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2409 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2410 *nodes[0].connect_style.borrow_mut() = ConnectStyle::FullBlockViaListen;
2411 // Create some new channels:
2412 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2414 // A pending HTLC which will be revoked:
2415 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2416 // Get the will-be-revoked local txn from nodes[0]
2417 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2418 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2419 assert_eq!(revoked_local_txn[0].input.len(), 1);
2420 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2421 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2422 assert_eq!(revoked_local_txn[1].input.len(), 1);
2423 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2424 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2425 // Revoke the old state
2426 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2429 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2431 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2432 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2433 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2435 check_spends!(node_txn[0], revoked_local_txn[0]);
2436 node_txn.swap_remove(0);
2438 check_added_monitors!(nodes[1], 1);
2439 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2440 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2442 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2443 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2444 // Verify broadcast of revoked HTLC-timeout
2445 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2446 check_added_monitors!(nodes[0], 1);
2447 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2448 // Broadcast revoked HTLC-timeout on node 1
2449 mine_transaction(&nodes[1], &node_txn[1]);
2450 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2452 get_announce_close_broadcast_events(&nodes, 0, 1);
2454 assert_eq!(nodes[0].node.list_channels().len(), 0);
2455 assert_eq!(nodes[1].node.list_channels().len(), 0);
2457 // We test justice_tx build by A on B's revoked HTLC-Success tx
2458 // Create some new channels:
2459 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2461 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2465 // A pending HTLC which will be revoked:
2466 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2467 // Get the will-be-revoked local txn from B
2468 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2469 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2470 assert_eq!(revoked_local_txn[0].input.len(), 1);
2471 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2472 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2473 // Revoke the old state
2474 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2476 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2478 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2479 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2480 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2482 check_spends!(node_txn[0], revoked_local_txn[0]);
2483 node_txn.swap_remove(0);
2485 check_added_monitors!(nodes[0], 1);
2486 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2488 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2489 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2490 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2491 check_added_monitors!(nodes[1], 1);
2492 mine_transaction(&nodes[0], &node_txn[1]);
2493 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2494 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2496 get_announce_close_broadcast_events(&nodes, 0, 1);
2497 assert_eq!(nodes[0].node.list_channels().len(), 0);
2498 assert_eq!(nodes[1].node.list_channels().len(), 0);
2502 fn revoked_output_claim() {
2503 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2504 // transaction is broadcast by its counterparty
2505 let chanmon_cfgs = create_chanmon_cfgs(2);
2506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2509 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2510 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2511 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2512 assert_eq!(revoked_local_txn.len(), 1);
2513 // Only output is the full channel value back to nodes[0]:
2514 assert_eq!(revoked_local_txn[0].output.len(), 1);
2515 // Send a payment through, updating everyone's latest commitment txn
2516 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2518 // Inform nodes[1] that nodes[0] broadcast a stale tx
2519 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2520 check_added_monitors!(nodes[1], 1);
2521 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2522 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2523 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2525 check_spends!(node_txn[0], revoked_local_txn[0]);
2527 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2528 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2529 get_announce_close_broadcast_events(&nodes, 0, 1);
2530 check_added_monitors!(nodes[0], 1);
2531 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2535 fn claim_htlc_outputs_shared_tx() {
2536 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2537 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2538 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2543 // Create some new channel:
2544 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2546 // Rebalance the network to generate htlc in the two directions
2547 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2548 // 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
2549 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2550 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2552 // Get the will-be-revoked local txn from node[0]
2553 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2554 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2555 assert_eq!(revoked_local_txn[0].input.len(), 1);
2556 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2557 assert_eq!(revoked_local_txn[1].input.len(), 1);
2558 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2559 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2560 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2562 //Revoke the old state
2563 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2566 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2567 check_added_monitors!(nodes[0], 1);
2568 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2569 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2570 check_added_monitors!(nodes[1], 1);
2571 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2572 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2573 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2575 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2576 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2578 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2579 check_spends!(node_txn[0], revoked_local_txn[0]);
2581 let mut witness_lens = BTreeSet::new();
2582 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2583 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2584 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2585 assert_eq!(witness_lens.len(), 3);
2586 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2587 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2588 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2590 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2591 // ANTI_REORG_DELAY confirmations.
2592 mine_transaction(&nodes[1], &node_txn[0]);
2593 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2594 expect_payment_failed!(nodes[1], payment_hash_2, false);
2596 get_announce_close_broadcast_events(&nodes, 0, 1);
2597 assert_eq!(nodes[0].node.list_channels().len(), 0);
2598 assert_eq!(nodes[1].node.list_channels().len(), 0);
2602 fn claim_htlc_outputs_single_tx() {
2603 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2604 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2605 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2608 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2610 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2612 // Rebalance the network to generate htlc in the two directions
2613 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2614 // 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
2615 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2616 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2617 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2619 // Get the will-be-revoked local txn from node[0]
2620 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2622 //Revoke the old state
2623 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2626 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2627 check_added_monitors!(nodes[0], 1);
2628 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2629 check_added_monitors!(nodes[1], 1);
2630 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2631 let mut events = nodes[0].node.get_and_clear_pending_events();
2632 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2633 match events.last().unwrap() {
2634 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2635 _ => panic!("Unexpected event"),
2638 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2639 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2641 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2642 assert_eq!(node_txn.len(), 7);
2644 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2645 assert_eq!(node_txn[0].input.len(), 1);
2646 check_spends!(node_txn[0], chan_1.3);
2647 assert_eq!(node_txn[1].input.len(), 1);
2648 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2649 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2650 check_spends!(node_txn[1], node_txn[0]);
2652 // Justice transactions are indices 2-3-4
2653 assert_eq!(node_txn[2].input.len(), 1);
2654 assert_eq!(node_txn[3].input.len(), 1);
2655 assert_eq!(node_txn[4].input.len(), 1);
2657 check_spends!(node_txn[2], revoked_local_txn[0]);
2658 check_spends!(node_txn[3], revoked_local_txn[0]);
2659 check_spends!(node_txn[4], revoked_local_txn[0]);
2661 let mut witness_lens = BTreeSet::new();
2662 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2663 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2664 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2665 assert_eq!(witness_lens.len(), 3);
2666 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2667 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2668 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2670 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2671 // ANTI_REORG_DELAY confirmations.
2672 mine_transaction(&nodes[1], &node_txn[2]);
2673 mine_transaction(&nodes[1], &node_txn[3]);
2674 mine_transaction(&nodes[1], &node_txn[4]);
2675 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2676 expect_payment_failed!(nodes[1], payment_hash_2, false);
2678 get_announce_close_broadcast_events(&nodes, 0, 1);
2679 assert_eq!(nodes[0].node.list_channels().len(), 0);
2680 assert_eq!(nodes[1].node.list_channels().len(), 0);
2684 fn test_htlc_on_chain_success() {
2685 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2686 // the preimage backward accordingly. So here we test that ChannelManager is
2687 // broadcasting the right event to other nodes in payment path.
2688 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2689 // A --------------------> B ----------------------> C (preimage)
2690 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2691 // commitment transaction was broadcast.
2692 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2694 // B should be able to claim via preimage if A then broadcasts its local tx.
2695 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2696 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2697 // PaymentSent event).
2699 let chanmon_cfgs = create_chanmon_cfgs(3);
2700 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2701 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2702 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2704 // Create some initial channels
2705 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2706 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2708 // Ensure all nodes are at the same height
2709 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2710 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2711 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2712 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2714 // Rebalance the network a bit by relaying one payment through all the channels...
2715 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2716 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2718 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2719 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2721 // Broadcast legit commitment tx from C on B's chain
2722 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2723 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2724 assert_eq!(commitment_tx.len(), 1);
2725 check_spends!(commitment_tx[0], chan_2.3);
2726 nodes[2].node.claim_funds(our_payment_preimage);
2727 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2728 nodes[2].node.claim_funds(our_payment_preimage_2);
2729 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2730 check_added_monitors!(nodes[2], 2);
2731 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2732 assert!(updates.update_add_htlcs.is_empty());
2733 assert!(updates.update_fail_htlcs.is_empty());
2734 assert!(updates.update_fail_malformed_htlcs.is_empty());
2735 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2737 mine_transaction(&nodes[2], &commitment_tx[0]);
2738 check_closed_broadcast!(nodes[2], true);
2739 check_added_monitors!(nodes[2], 1);
2740 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2741 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2742 assert_eq!(node_txn.len(), 2);
2743 check_spends!(node_txn[0], commitment_tx[0]);
2744 check_spends!(node_txn[1], commitment_tx[0]);
2745 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2746 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2747 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2748 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2749 assert_eq!(node_txn[0].lock_time.0, 0);
2750 assert_eq!(node_txn[1].lock_time.0, 0);
2752 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2753 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2754 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]});
2755 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2757 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2758 assert_eq!(added_monitors.len(), 1);
2759 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2760 added_monitors.clear();
2762 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2763 assert_eq!(forwarded_events.len(), 3);
2764 match forwarded_events[0] {
2765 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2766 _ => panic!("Unexpected event"),
2768 let chan_id = Some(chan_1.2);
2769 match forwarded_events[1] {
2770 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2771 assert_eq!(fee_earned_msat, Some(1000));
2772 assert_eq!(prev_channel_id, chan_id);
2773 assert_eq!(claim_from_onchain_tx, true);
2774 assert_eq!(next_channel_id, Some(chan_2.2));
2775 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2779 match forwarded_events[2] {
2780 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2781 assert_eq!(fee_earned_msat, Some(1000));
2782 assert_eq!(prev_channel_id, chan_id);
2783 assert_eq!(claim_from_onchain_tx, true);
2784 assert_eq!(next_channel_id, Some(chan_2.2));
2785 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2789 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2791 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2792 assert_eq!(added_monitors.len(), 2);
2793 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2794 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2795 added_monitors.clear();
2797 assert_eq!(events.len(), 3);
2799 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2800 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2802 match nodes_2_event {
2803 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2804 _ => panic!("Unexpected event"),
2807 match nodes_0_event {
2808 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, .. } } => {
2809 assert!(update_add_htlcs.is_empty());
2810 assert!(update_fail_htlcs.is_empty());
2811 assert_eq!(update_fulfill_htlcs.len(), 1);
2812 assert!(update_fail_malformed_htlcs.is_empty());
2813 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2815 _ => panic!("Unexpected event"),
2818 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2820 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2821 _ => panic!("Unexpected event"),
2824 macro_rules! check_tx_local_broadcast {
2825 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2826 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2827 assert_eq!(node_txn.len(), 2);
2828 // Node[1]: 2 * HTLC-timeout tx
2829 // Node[0]: 2 * HTLC-timeout tx
2830 check_spends!(node_txn[0], $commitment_tx);
2831 check_spends!(node_txn[1], $commitment_tx);
2832 assert_ne!(node_txn[0].lock_time.0, 0);
2833 assert_ne!(node_txn[1].lock_time.0, 0);
2835 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2836 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2837 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2838 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2840 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2843 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2848 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2849 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2851 // Broadcast legit commitment tx from A on B's chain
2852 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2853 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2854 check_spends!(node_a_commitment_tx[0], chan_1.3);
2855 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2856 check_closed_broadcast!(nodes[1], true);
2857 check_added_monitors!(nodes[1], 1);
2858 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2859 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2860 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2861 let commitment_spend =
2862 if node_txn.len() == 1 {
2865 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2866 // FullBlockViaListen
2867 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2868 check_spends!(node_txn[1], commitment_tx[0]);
2869 check_spends!(node_txn[2], commitment_tx[0]);
2870 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2873 check_spends!(node_txn[0], commitment_tx[0]);
2874 check_spends!(node_txn[1], commitment_tx[0]);
2875 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2880 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2881 assert_eq!(commitment_spend.input.len(), 2);
2882 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2883 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
2885 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2886 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2887 // we already checked the same situation with A.
2889 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2890 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
2891 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2892 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2893 check_closed_broadcast!(nodes[0], true);
2894 check_added_monitors!(nodes[0], 1);
2895 let events = nodes[0].node.get_and_clear_pending_events();
2896 assert_eq!(events.len(), 5);
2897 let mut first_claimed = false;
2898 for event in events {
2900 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2901 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2902 assert!(!first_claimed);
2903 first_claimed = true;
2905 assert_eq!(payment_preimage, our_payment_preimage_2);
2906 assert_eq!(payment_hash, payment_hash_2);
2909 Event::PaymentPathSuccessful { .. } => {},
2910 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2911 _ => panic!("Unexpected event"),
2914 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2917 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2918 // Test that in case of a unilateral close onchain, we detect the state of output and
2919 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2920 // broadcasting the right event to other nodes in payment path.
2921 // A ------------------> B ----------------------> C (timeout)
2922 // B's commitment tx C's commitment tx
2924 // B's HTLC timeout tx B's timeout tx
2926 let chanmon_cfgs = create_chanmon_cfgs(3);
2927 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2928 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2929 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2930 *nodes[0].connect_style.borrow_mut() = connect_style;
2931 *nodes[1].connect_style.borrow_mut() = connect_style;
2932 *nodes[2].connect_style.borrow_mut() = connect_style;
2934 // Create some intial channels
2935 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2936 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2938 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2939 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2940 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2942 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2944 // Broadcast legit commitment tx from C on B's chain
2945 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2946 check_spends!(commitment_tx[0], chan_2.3);
2947 nodes[2].node.fail_htlc_backwards(&payment_hash);
2948 check_added_monitors!(nodes[2], 0);
2949 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2950 check_added_monitors!(nodes[2], 1);
2952 let events = nodes[2].node.get_and_clear_pending_msg_events();
2953 assert_eq!(events.len(), 1);
2955 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, .. } } => {
2956 assert!(update_add_htlcs.is_empty());
2957 assert!(!update_fail_htlcs.is_empty());
2958 assert!(update_fulfill_htlcs.is_empty());
2959 assert!(update_fail_malformed_htlcs.is_empty());
2960 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2962 _ => panic!("Unexpected event"),
2964 mine_transaction(&nodes[2], &commitment_tx[0]);
2965 check_closed_broadcast!(nodes[2], true);
2966 check_added_monitors!(nodes[2], 1);
2967 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2968 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2969 assert_eq!(node_txn.len(), 0);
2971 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2972 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2973 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2974 mine_transaction(&nodes[1], &commitment_tx[0]);
2975 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2978 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2979 assert_eq!(node_txn.len(), 3); // 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2981 check_spends!(node_txn[2], commitment_tx[0]);
2982 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2984 check_spends!(node_txn[0], chan_2.3);
2985 check_spends!(node_txn[1], node_txn[0]);
2986 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2987 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2989 timeout_tx = node_txn[2].clone();
2993 mine_transaction(&nodes[1], &timeout_tx);
2994 check_added_monitors!(nodes[1], 1);
2995 check_closed_broadcast!(nodes[1], true);
2997 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2999 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 }]);
3000 check_added_monitors!(nodes[1], 1);
3001 let events = nodes[1].node.get_and_clear_pending_msg_events();
3002 assert_eq!(events.len(), 1);
3004 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, .. } } => {
3005 assert!(update_add_htlcs.is_empty());
3006 assert!(!update_fail_htlcs.is_empty());
3007 assert!(update_fulfill_htlcs.is_empty());
3008 assert!(update_fail_malformed_htlcs.is_empty());
3009 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3011 _ => panic!("Unexpected event"),
3014 // Broadcast legit commitment tx from B on A's chain
3015 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3016 check_spends!(commitment_tx[0], chan_1.3);
3018 mine_transaction(&nodes[0], &commitment_tx[0]);
3019 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3021 check_closed_broadcast!(nodes[0], true);
3022 check_added_monitors!(nodes[0], 1);
3023 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3024 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3025 assert_eq!(node_txn.len(), 1);
3026 check_spends!(node_txn[0], commitment_tx[0]);
3027 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3031 fn test_htlc_on_chain_timeout() {
3032 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3033 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3034 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3038 fn test_simple_commitment_revoked_fail_backward() {
3039 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3040 // and fail backward accordingly.
3042 let chanmon_cfgs = create_chanmon_cfgs(3);
3043 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3044 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3045 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3047 // Create some initial channels
3048 create_announced_chan_between_nodes(&nodes, 0, 1);
3049 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3051 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3052 // Get the will-be-revoked local txn from nodes[2]
3053 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3054 // Revoke the old state
3055 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3057 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3059 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3060 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3061 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3062 check_added_monitors!(nodes[1], 1);
3063 check_closed_broadcast!(nodes[1], true);
3065 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 }]);
3066 check_added_monitors!(nodes[1], 1);
3067 let events = nodes[1].node.get_and_clear_pending_msg_events();
3068 assert_eq!(events.len(), 1);
3070 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, .. } } => {
3071 assert!(update_add_htlcs.is_empty());
3072 assert_eq!(update_fail_htlcs.len(), 1);
3073 assert!(update_fulfill_htlcs.is_empty());
3074 assert!(update_fail_malformed_htlcs.is_empty());
3075 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3077 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3078 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3079 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3081 _ => panic!("Unexpected event"),
3085 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3086 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3087 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3088 // commitment transaction anymore.
3089 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3090 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3091 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3092 // technically disallowed and we should probably handle it reasonably.
3093 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3094 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3096 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3097 // commitment_signed (implying it will be in the latest remote commitment transaction).
3098 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3099 // and once they revoke the previous commitment transaction (allowing us to send a new
3100 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3101 let chanmon_cfgs = create_chanmon_cfgs(3);
3102 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3103 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3104 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3106 // Create some initial channels
3107 create_announced_chan_between_nodes(&nodes, 0, 1);
3108 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3110 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 });
3111 // Get the will-be-revoked local txn from nodes[2]
3112 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3113 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3114 // Revoke the old state
3115 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3117 let value = if use_dust {
3118 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3119 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3120 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3121 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3124 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3125 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3126 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3128 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3129 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3130 check_added_monitors!(nodes[2], 1);
3131 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3132 assert!(updates.update_add_htlcs.is_empty());
3133 assert!(updates.update_fulfill_htlcs.is_empty());
3134 assert!(updates.update_fail_malformed_htlcs.is_empty());
3135 assert_eq!(updates.update_fail_htlcs.len(), 1);
3136 assert!(updates.update_fee.is_none());
3137 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3138 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3139 // Drop the last RAA from 3 -> 2
3141 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3142 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3143 check_added_monitors!(nodes[2], 1);
3144 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3145 assert!(updates.update_add_htlcs.is_empty());
3146 assert!(updates.update_fulfill_htlcs.is_empty());
3147 assert!(updates.update_fail_malformed_htlcs.is_empty());
3148 assert_eq!(updates.update_fail_htlcs.len(), 1);
3149 assert!(updates.update_fee.is_none());
3150 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3151 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3152 check_added_monitors!(nodes[1], 1);
3153 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3154 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3155 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3156 check_added_monitors!(nodes[2], 1);
3158 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3159 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3160 check_added_monitors!(nodes[2], 1);
3161 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3162 assert!(updates.update_add_htlcs.is_empty());
3163 assert!(updates.update_fulfill_htlcs.is_empty());
3164 assert!(updates.update_fail_malformed_htlcs.is_empty());
3165 assert_eq!(updates.update_fail_htlcs.len(), 1);
3166 assert!(updates.update_fee.is_none());
3167 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3168 // At this point first_payment_hash has dropped out of the latest two commitment
3169 // transactions that nodes[1] is tracking...
3170 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3171 check_added_monitors!(nodes[1], 1);
3172 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3174 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3175 check_added_monitors!(nodes[2], 1);
3177 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3178 // on nodes[2]'s RAA.
3179 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3180 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3181 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3182 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3183 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3184 check_added_monitors!(nodes[1], 0);
3187 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3188 // One monitor for the new revocation preimage, no second on as we won't generate a new
3189 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3190 check_added_monitors!(nodes[1], 1);
3191 let events = nodes[1].node.get_and_clear_pending_events();
3192 assert_eq!(events.len(), 2);
3194 Event::PendingHTLCsForwardable { .. } => { },
3195 _ => panic!("Unexpected event"),
3198 Event::HTLCHandlingFailed { .. } => { },
3199 _ => panic!("Unexpected event"),
3201 // Deliberately don't process the pending fail-back so they all fail back at once after
3202 // block connection just like the !deliver_bs_raa case
3205 let mut failed_htlcs = HashSet::new();
3206 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3208 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3209 check_added_monitors!(nodes[1], 1);
3210 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3212 let events = nodes[1].node.get_and_clear_pending_events();
3213 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3215 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3216 _ => panic!("Unexepected event"),
3219 Event::PaymentPathFailed { ref payment_hash, .. } => {
3220 assert_eq!(*payment_hash, fourth_payment_hash);
3222 _ => panic!("Unexpected event"),
3225 Event::PaymentFailed { ref payment_hash, .. } => {
3226 assert_eq!(*payment_hash, fourth_payment_hash);
3228 _ => panic!("Unexpected event"),
3231 nodes[1].node.process_pending_htlc_forwards();
3232 check_added_monitors!(nodes[1], 1);
3234 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3235 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3238 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3239 match nodes_2_event {
3240 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, .. } } => {
3241 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3242 assert_eq!(update_add_htlcs.len(), 1);
3243 assert!(update_fulfill_htlcs.is_empty());
3244 assert!(update_fail_htlcs.is_empty());
3245 assert!(update_fail_malformed_htlcs.is_empty());
3247 _ => panic!("Unexpected event"),
3251 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3252 match nodes_2_event {
3253 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3254 assert_eq!(channel_id, chan_2.2);
3255 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3257 _ => panic!("Unexpected event"),
3260 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3261 match nodes_0_event {
3262 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, .. } } => {
3263 assert!(update_add_htlcs.is_empty());
3264 assert_eq!(update_fail_htlcs.len(), 3);
3265 assert!(update_fulfill_htlcs.is_empty());
3266 assert!(update_fail_malformed_htlcs.is_empty());
3267 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3269 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3270 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3271 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3273 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3275 let events = nodes[0].node.get_and_clear_pending_events();
3276 assert_eq!(events.len(), 6);
3278 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3279 assert!(failed_htlcs.insert(payment_hash.0));
3280 // If we delivered B's RAA we got an unknown preimage error, not something
3281 // that we should update our routing table for.
3282 if !deliver_bs_raa {
3283 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3286 _ => panic!("Unexpected event"),
3289 Event::PaymentFailed { ref payment_hash, .. } => {
3290 assert_eq!(*payment_hash, first_payment_hash);
3292 _ => panic!("Unexpected event"),
3295 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3296 assert!(failed_htlcs.insert(payment_hash.0));
3298 _ => panic!("Unexpected event"),
3301 Event::PaymentFailed { ref payment_hash, .. } => {
3302 assert_eq!(*payment_hash, second_payment_hash);
3304 _ => panic!("Unexpected event"),
3307 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3308 assert!(failed_htlcs.insert(payment_hash.0));
3310 _ => panic!("Unexpected event"),
3313 Event::PaymentFailed { ref payment_hash, .. } => {
3314 assert_eq!(*payment_hash, third_payment_hash);
3316 _ => panic!("Unexpected event"),
3319 _ => panic!("Unexpected event"),
3322 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3324 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3325 _ => panic!("Unexpected event"),
3328 assert!(failed_htlcs.contains(&first_payment_hash.0));
3329 assert!(failed_htlcs.contains(&second_payment_hash.0));
3330 assert!(failed_htlcs.contains(&third_payment_hash.0));
3334 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3335 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3336 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3337 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3338 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3342 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3343 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3344 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3345 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3346 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3350 fn fail_backward_pending_htlc_upon_channel_failure() {
3351 let chanmon_cfgs = create_chanmon_cfgs(2);
3352 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3353 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3354 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3355 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3357 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3359 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3360 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3361 PaymentId(payment_hash.0)).unwrap();
3362 check_added_monitors!(nodes[0], 1);
3364 let payment_event = {
3365 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3366 assert_eq!(events.len(), 1);
3367 SendEvent::from_event(events.remove(0))
3369 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3370 assert_eq!(payment_event.msgs.len(), 1);
3373 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3374 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3376 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3377 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3378 check_added_monitors!(nodes[0], 0);
3380 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3383 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3385 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3387 let secp_ctx = Secp256k1::new();
3388 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3389 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3390 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3391 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3392 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3393 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3395 // Send a 0-msat update_add_htlc to fail the channel.
3396 let update_add_htlc = msgs::UpdateAddHTLC {
3402 onion_routing_packet,
3404 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3406 let events = nodes[0].node.get_and_clear_pending_events();
3407 assert_eq!(events.len(), 3);
3408 // Check that Alice fails backward the pending HTLC from the second payment.
3410 Event::PaymentPathFailed { payment_hash, .. } => {
3411 assert_eq!(payment_hash, failed_payment_hash);
3413 _ => panic!("Unexpected event"),
3416 Event::PaymentFailed { payment_hash, .. } => {
3417 assert_eq!(payment_hash, failed_payment_hash);
3419 _ => panic!("Unexpected event"),
3422 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3423 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3425 _ => panic!("Unexpected event {:?}", events[1]),
3427 check_closed_broadcast!(nodes[0], true);
3428 check_added_monitors!(nodes[0], 1);
3432 fn test_htlc_ignore_latest_remote_commitment() {
3433 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3434 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3435 let chanmon_cfgs = create_chanmon_cfgs(2);
3436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3439 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3440 // We rely on the ability to connect a block redundantly, which isn't allowed via
3441 // `chain::Listen`, so we never run the test if we randomly get assigned that
3445 create_announced_chan_between_nodes(&nodes, 0, 1);
3447 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3448 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3449 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3450 check_closed_broadcast!(nodes[0], true);
3451 check_added_monitors!(nodes[0], 1);
3452 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3454 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3455 assert_eq!(node_txn.len(), 3);
3456 assert_eq!(node_txn[0], node_txn[1]);
3458 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
3459 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3460 check_closed_broadcast!(nodes[1], true);
3461 check_added_monitors!(nodes[1], 1);
3462 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3464 // Duplicate the connect_block call since this may happen due to other listeners
3465 // registering new transactions
3466 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3470 fn test_force_close_fail_back() {
3471 // Check which HTLCs are failed-backwards on channel force-closure
3472 let chanmon_cfgs = create_chanmon_cfgs(3);
3473 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3474 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3475 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3476 create_announced_chan_between_nodes(&nodes, 0, 1);
3477 create_announced_chan_between_nodes(&nodes, 1, 2);
3479 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3481 let mut payment_event = {
3482 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3483 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3484 check_added_monitors!(nodes[0], 1);
3486 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3487 assert_eq!(events.len(), 1);
3488 SendEvent::from_event(events.remove(0))
3491 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3492 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3494 expect_pending_htlcs_forwardable!(nodes[1]);
3496 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3497 assert_eq!(events_2.len(), 1);
3498 payment_event = SendEvent::from_event(events_2.remove(0));
3499 assert_eq!(payment_event.msgs.len(), 1);
3501 check_added_monitors!(nodes[1], 1);
3502 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3503 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3504 check_added_monitors!(nodes[2], 1);
3505 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3507 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3508 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3509 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3511 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3512 check_closed_broadcast!(nodes[2], true);
3513 check_added_monitors!(nodes[2], 1);
3514 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3516 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3517 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3518 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3519 // back to nodes[1] upon timeout otherwise.
3520 assert_eq!(node_txn.len(), 1);
3524 mine_transaction(&nodes[1], &tx);
3526 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3527 check_closed_broadcast!(nodes[1], true);
3528 check_added_monitors!(nodes[1], 1);
3529 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3531 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3533 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3534 .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);
3536 mine_transaction(&nodes[2], &tx);
3537 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3538 assert_eq!(node_txn.len(), 1);
3539 assert_eq!(node_txn[0].input.len(), 1);
3540 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3541 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3542 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3544 check_spends!(node_txn[0], tx);
3548 fn test_dup_events_on_peer_disconnect() {
3549 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3550 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3551 // as we used to generate the event immediately upon receipt of the payment preimage in the
3552 // update_fulfill_htlc message.
3554 let chanmon_cfgs = create_chanmon_cfgs(2);
3555 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3556 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3557 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3558 create_announced_chan_between_nodes(&nodes, 0, 1);
3560 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3562 nodes[1].node.claim_funds(payment_preimage);
3563 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3564 check_added_monitors!(nodes[1], 1);
3565 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3566 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3567 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3569 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3570 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3572 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573 expect_payment_path_successful!(nodes[0]);
3577 fn test_peer_disconnected_before_funding_broadcasted() {
3578 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3579 // before the funding transaction has been broadcasted.
3580 let chanmon_cfgs = create_chanmon_cfgs(2);
3581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3585 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3586 // broadcasted, even though it's created by `nodes[0]`.
3587 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();
3588 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3589 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3590 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3591 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3593 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3594 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3596 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3598 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3599 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3601 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3602 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3605 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3608 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3609 // disconnected before the funding transaction was broadcasted.
3610 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3611 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3613 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3614 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3618 fn test_simple_peer_disconnect() {
3619 // Test that we can reconnect when there are no lost messages
3620 let chanmon_cfgs = create_chanmon_cfgs(3);
3621 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3622 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3623 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3624 create_announced_chan_between_nodes(&nodes, 0, 1);
3625 create_announced_chan_between_nodes(&nodes, 1, 2);
3627 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3628 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3629 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3631 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3632 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3633 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3634 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3636 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3637 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3638 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3640 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3641 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3642 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3643 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3645 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3646 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3648 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3649 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3651 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3653 let events = nodes[0].node.get_and_clear_pending_events();
3654 assert_eq!(events.len(), 4);
3656 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3657 assert_eq!(payment_preimage, payment_preimage_3);
3658 assert_eq!(payment_hash, payment_hash_3);
3660 _ => panic!("Unexpected event"),
3663 Event::PaymentPathSuccessful { .. } => {},
3664 _ => panic!("Unexpected event"),
3667 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3668 assert_eq!(payment_hash, payment_hash_5);
3669 assert!(payment_failed_permanently);
3671 _ => panic!("Unexpected event"),
3674 Event::PaymentFailed { payment_hash, .. } => {
3675 assert_eq!(payment_hash, payment_hash_5);
3677 _ => panic!("Unexpected event"),
3681 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3682 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3685 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3686 // Test that we can reconnect when in-flight HTLC updates get dropped
3687 let chanmon_cfgs = create_chanmon_cfgs(2);
3688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3690 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3692 let mut as_channel_ready = None;
3693 let channel_id = if messages_delivered == 0 {
3694 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3695 as_channel_ready = Some(channel_ready);
3696 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3697 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3698 // it before the channel_reestablish message.
3701 create_announced_chan_between_nodes(&nodes, 0, 1).2
3704 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3706 let payment_event = {
3707 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3708 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3709 check_added_monitors!(nodes[0], 1);
3711 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3712 assert_eq!(events.len(), 1);
3713 SendEvent::from_event(events.remove(0))
3715 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3717 if messages_delivered < 2 {
3718 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3720 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3721 if messages_delivered >= 3 {
3722 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3723 check_added_monitors!(nodes[1], 1);
3724 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3726 if messages_delivered >= 4 {
3727 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3728 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3729 check_added_monitors!(nodes[0], 1);
3731 if messages_delivered >= 5 {
3732 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3733 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3734 // No commitment_signed so get_event_msg's assert(len == 1) passes
3735 check_added_monitors!(nodes[0], 1);
3737 if messages_delivered >= 6 {
3738 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3739 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3740 check_added_monitors!(nodes[1], 1);
3747 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3748 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3749 if messages_delivered < 3 {
3750 if simulate_broken_lnd {
3751 // lnd has a long-standing bug where they send a channel_ready prior to a
3752 // channel_reestablish if you reconnect prior to channel_ready time.
3754 // Here we simulate that behavior, delivering a channel_ready immediately on
3755 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3756 // in `reconnect_nodes` but we currently don't fail based on that.
3758 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3759 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3761 // Even if the channel_ready messages get exchanged, as long as nothing further was
3762 // received on either side, both sides will need to resend them.
3763 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3764 } else if messages_delivered == 3 {
3765 // nodes[0] still wants its RAA + commitment_signed
3766 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3767 } else if messages_delivered == 4 {
3768 // nodes[0] still wants its commitment_signed
3769 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3770 } else if messages_delivered == 5 {
3771 // nodes[1] still wants its final RAA
3772 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3773 } else if messages_delivered == 6 {
3774 // Everything was delivered...
3775 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3778 let events_1 = nodes[1].node.get_and_clear_pending_events();
3779 if messages_delivered == 0 {
3780 assert_eq!(events_1.len(), 2);
3782 Event::ChannelReady { .. } => { },
3783 _ => panic!("Unexpected event"),
3786 Event::PendingHTLCsForwardable { .. } => { },
3787 _ => panic!("Unexpected event"),
3790 assert_eq!(events_1.len(), 1);
3792 Event::PendingHTLCsForwardable { .. } => { },
3793 _ => panic!("Unexpected event"),
3797 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3798 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3799 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3801 nodes[1].node.process_pending_htlc_forwards();
3803 let events_2 = nodes[1].node.get_and_clear_pending_events();
3804 assert_eq!(events_2.len(), 1);
3806 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3807 assert_eq!(payment_hash_1, *payment_hash);
3808 assert_eq!(amount_msat, 1_000_000);
3809 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3810 assert_eq!(via_channel_id, Some(channel_id));
3812 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3813 assert!(payment_preimage.is_none());
3814 assert_eq!(payment_secret_1, *payment_secret);
3816 _ => panic!("expected PaymentPurpose::InvoicePayment")
3819 _ => panic!("Unexpected event"),
3822 nodes[1].node.claim_funds(payment_preimage_1);
3823 check_added_monitors!(nodes[1], 1);
3824 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3826 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3827 assert_eq!(events_3.len(), 1);
3828 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3829 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3830 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3831 assert!(updates.update_add_htlcs.is_empty());
3832 assert!(updates.update_fail_htlcs.is_empty());
3833 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3834 assert!(updates.update_fail_malformed_htlcs.is_empty());
3835 assert!(updates.update_fee.is_none());
3836 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3838 _ => panic!("Unexpected event"),
3841 if messages_delivered >= 1 {
3842 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3844 let events_4 = nodes[0].node.get_and_clear_pending_events();
3845 assert_eq!(events_4.len(), 1);
3847 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3848 assert_eq!(payment_preimage_1, *payment_preimage);
3849 assert_eq!(payment_hash_1, *payment_hash);
3851 _ => panic!("Unexpected event"),
3854 if messages_delivered >= 2 {
3855 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3856 check_added_monitors!(nodes[0], 1);
3857 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3859 if messages_delivered >= 3 {
3860 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3861 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3862 check_added_monitors!(nodes[1], 1);
3864 if messages_delivered >= 4 {
3865 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3866 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3867 // No commitment_signed so get_event_msg's assert(len == 1) passes
3868 check_added_monitors!(nodes[1], 1);
3870 if messages_delivered >= 5 {
3871 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3872 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3873 check_added_monitors!(nodes[0], 1);
3880 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3881 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3882 if messages_delivered < 2 {
3883 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3884 if messages_delivered < 1 {
3885 expect_payment_sent!(nodes[0], payment_preimage_1);
3887 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3889 } else if messages_delivered == 2 {
3890 // nodes[0] still wants its RAA + commitment_signed
3891 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3892 } else if messages_delivered == 3 {
3893 // nodes[0] still wants its commitment_signed
3894 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3895 } else if messages_delivered == 4 {
3896 // nodes[1] still wants its final RAA
3897 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3898 } else if messages_delivered == 5 {
3899 // Everything was delivered...
3900 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3903 if messages_delivered == 1 || messages_delivered == 2 {
3904 expect_payment_path_successful!(nodes[0]);
3906 if messages_delivered <= 5 {
3907 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3908 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3910 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3912 if messages_delivered > 2 {
3913 expect_payment_path_successful!(nodes[0]);
3916 // Channel should still work fine...
3917 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3918 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3919 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3923 fn test_drop_messages_peer_disconnect_a() {
3924 do_test_drop_messages_peer_disconnect(0, true);
3925 do_test_drop_messages_peer_disconnect(0, false);
3926 do_test_drop_messages_peer_disconnect(1, false);
3927 do_test_drop_messages_peer_disconnect(2, false);
3931 fn test_drop_messages_peer_disconnect_b() {
3932 do_test_drop_messages_peer_disconnect(3, false);
3933 do_test_drop_messages_peer_disconnect(4, false);
3934 do_test_drop_messages_peer_disconnect(5, false);
3935 do_test_drop_messages_peer_disconnect(6, false);
3939 fn test_channel_ready_without_best_block_updated() {
3940 // Previously, if we were offline when a funding transaction was locked in, and then we came
3941 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3942 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3943 // channel_ready immediately instead.
3944 let chanmon_cfgs = create_chanmon_cfgs(2);
3945 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3946 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3947 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3948 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3950 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3952 let conf_height = nodes[0].best_block_info().1 + 1;
3953 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3954 let block_txn = [funding_tx];
3955 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3956 let conf_block_header = nodes[0].get_block_header(conf_height);
3957 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3959 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3960 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3961 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3965 fn test_drop_messages_peer_disconnect_dual_htlc() {
3966 // Test that we can handle reconnecting when both sides of a channel have pending
3967 // commitment_updates when we disconnect.
3968 let chanmon_cfgs = create_chanmon_cfgs(2);
3969 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3970 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3971 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3972 create_announced_chan_between_nodes(&nodes, 0, 1);
3974 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3976 // Now try to send a second payment which will fail to send
3977 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3978 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3979 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3980 check_added_monitors!(nodes[0], 1);
3982 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3983 assert_eq!(events_1.len(), 1);
3985 MessageSendEvent::UpdateHTLCs { .. } => {},
3986 _ => panic!("Unexpected event"),
3989 nodes[1].node.claim_funds(payment_preimage_1);
3990 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3991 check_added_monitors!(nodes[1], 1);
3993 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3994 assert_eq!(events_2.len(), 1);
3996 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 } } => {
3997 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3998 assert!(update_add_htlcs.is_empty());
3999 assert_eq!(update_fulfill_htlcs.len(), 1);
4000 assert!(update_fail_htlcs.is_empty());
4001 assert!(update_fail_malformed_htlcs.is_empty());
4002 assert!(update_fee.is_none());
4004 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4005 let events_3 = nodes[0].node.get_and_clear_pending_events();
4006 assert_eq!(events_3.len(), 1);
4008 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4009 assert_eq!(*payment_preimage, payment_preimage_1);
4010 assert_eq!(*payment_hash, payment_hash_1);
4012 _ => panic!("Unexpected event"),
4015 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4016 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4017 // No commitment_signed so get_event_msg's assert(len == 1) passes
4018 check_added_monitors!(nodes[0], 1);
4020 _ => panic!("Unexpected event"),
4023 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4024 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4026 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();
4027 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4028 assert_eq!(reestablish_1.len(), 1);
4029 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();
4030 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4031 assert_eq!(reestablish_2.len(), 1);
4033 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4034 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4035 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4036 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4038 assert!(as_resp.0.is_none());
4039 assert!(bs_resp.0.is_none());
4041 assert!(bs_resp.1.is_none());
4042 assert!(bs_resp.2.is_none());
4044 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4046 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4047 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4048 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4049 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4050 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4051 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4052 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4053 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4054 // No commitment_signed so get_event_msg's assert(len == 1) passes
4055 check_added_monitors!(nodes[1], 1);
4057 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4058 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4059 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4060 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4061 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4062 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4063 assert!(bs_second_commitment_signed.update_fee.is_none());
4064 check_added_monitors!(nodes[1], 1);
4066 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4067 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4068 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4069 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4070 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4071 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4072 assert!(as_commitment_signed.update_fee.is_none());
4073 check_added_monitors!(nodes[0], 1);
4075 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4076 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4077 // No commitment_signed so get_event_msg's assert(len == 1) passes
4078 check_added_monitors!(nodes[0], 1);
4080 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4081 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4082 // No commitment_signed so get_event_msg's assert(len == 1) passes
4083 check_added_monitors!(nodes[1], 1);
4085 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4086 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4087 check_added_monitors!(nodes[1], 1);
4089 expect_pending_htlcs_forwardable!(nodes[1]);
4091 let events_5 = nodes[1].node.get_and_clear_pending_events();
4092 assert_eq!(events_5.len(), 1);
4094 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4095 assert_eq!(payment_hash_2, *payment_hash);
4097 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4098 assert!(payment_preimage.is_none());
4099 assert_eq!(payment_secret_2, *payment_secret);
4101 _ => panic!("expected PaymentPurpose::InvoicePayment")
4104 _ => panic!("Unexpected event"),
4107 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4108 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4109 check_added_monitors!(nodes[0], 1);
4111 expect_payment_path_successful!(nodes[0]);
4112 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4115 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4116 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4117 // to avoid our counterparty failing the channel.
4118 let chanmon_cfgs = create_chanmon_cfgs(2);
4119 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4120 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4121 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4123 create_announced_chan_between_nodes(&nodes, 0, 1);
4125 let our_payment_hash = if send_partial_mpp {
4126 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4127 // Use the utility function send_payment_along_path to send the payment with MPP data which
4128 // indicates there are more HTLCs coming.
4129 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.
4130 let payment_id = PaymentId([42; 32]);
4131 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4132 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4133 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4134 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4135 &None, session_privs[0]).unwrap();
4136 check_added_monitors!(nodes[0], 1);
4137 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4138 assert_eq!(events.len(), 1);
4139 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4140 // hop should *not* yet generate any PaymentClaimable event(s).
4141 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4144 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4147 let mut block = Block {
4148 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
4151 connect_block(&nodes[0], &block);
4152 connect_block(&nodes[1], &block);
4153 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4154 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4155 block.header.prev_blockhash = block.block_hash();
4156 connect_block(&nodes[0], &block);
4157 connect_block(&nodes[1], &block);
4160 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4162 check_added_monitors!(nodes[1], 1);
4163 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4164 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4165 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4166 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4167 assert!(htlc_timeout_updates.update_fee.is_none());
4169 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4170 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4171 // 100_000 msat as u64, followed by the height at which we failed back above
4172 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4173 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4174 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4178 fn test_htlc_timeout() {
4179 do_test_htlc_timeout(true);
4180 do_test_htlc_timeout(false);
4183 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4184 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4185 let chanmon_cfgs = create_chanmon_cfgs(3);
4186 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4187 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4188 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4189 create_announced_chan_between_nodes(&nodes, 0, 1);
4190 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4192 // Make sure all nodes are at the same starting height
4193 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4194 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4195 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4197 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4198 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4199 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4200 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4201 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4202 check_added_monitors!(nodes[1], 1);
4204 // Now attempt to route a second payment, which should be placed in the holding cell
4205 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4206 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4207 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4208 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4210 check_added_monitors!(nodes[0], 1);
4211 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4212 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4213 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4214 expect_pending_htlcs_forwardable!(nodes[1]);
4216 check_added_monitors!(nodes[1], 0);
4218 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4219 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4220 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4221 connect_blocks(&nodes[1], 1);
4224 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 }]);
4225 check_added_monitors!(nodes[1], 1);
4226 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4227 assert_eq!(fail_commit.len(), 1);
4228 match fail_commit[0] {
4229 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4230 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4231 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4233 _ => unreachable!(),
4235 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4237 expect_payment_failed!(nodes[1], second_payment_hash, false);
4242 fn test_holding_cell_htlc_add_timeouts() {
4243 do_test_holding_cell_htlc_add_timeouts(false);
4244 do_test_holding_cell_htlc_add_timeouts(true);
4247 macro_rules! check_spendable_outputs {
4248 ($node: expr, $keysinterface: expr) => {
4250 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4251 let mut txn = Vec::new();
4252 let mut all_outputs = Vec::new();
4253 let secp_ctx = Secp256k1::new();
4254 for event in events.drain(..) {
4256 Event::SpendableOutputs { mut outputs } => {
4257 for outp in outputs.drain(..) {
4258 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4259 all_outputs.push(outp);
4262 _ => panic!("Unexpected event"),
4265 if all_outputs.len() > 1 {
4266 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) {
4276 fn test_claim_sizeable_push_msat() {
4277 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4278 let chanmon_cfgs = create_chanmon_cfgs(2);
4279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4281 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4283 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4284 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4285 check_closed_broadcast!(nodes[1], true);
4286 check_added_monitors!(nodes[1], 1);
4287 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4288 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4289 assert_eq!(node_txn.len(), 1);
4290 check_spends!(node_txn[0], chan.3);
4291 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
4293 mine_transaction(&nodes[1], &node_txn[0]);
4294 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4296 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4297 assert_eq!(spend_txn.len(), 1);
4298 assert_eq!(spend_txn[0].input.len(), 1);
4299 check_spends!(spend_txn[0], node_txn[0]);
4300 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4304 fn test_claim_on_remote_sizeable_push_msat() {
4305 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4306 // to_remote output is encumbered by a P2WPKH
4307 let chanmon_cfgs = create_chanmon_cfgs(2);
4308 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4309 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4310 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4312 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4313 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4314 check_closed_broadcast!(nodes[0], true);
4315 check_added_monitors!(nodes[0], 1);
4316 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4318 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4319 assert_eq!(node_txn.len(), 1);
4320 check_spends!(node_txn[0], chan.3);
4321 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
4323 mine_transaction(&nodes[1], &node_txn[0]);
4324 check_closed_broadcast!(nodes[1], true);
4325 check_added_monitors!(nodes[1], 1);
4326 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4327 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4329 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4330 assert_eq!(spend_txn.len(), 1);
4331 check_spends!(spend_txn[0], node_txn[0]);
4335 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4336 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4337 // to_remote output is encumbered by a P2WPKH
4339 let chanmon_cfgs = create_chanmon_cfgs(2);
4340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4342 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4344 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4345 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4346 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4347 assert_eq!(revoked_local_txn[0].input.len(), 1);
4348 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4350 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4351 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4352 check_closed_broadcast!(nodes[1], true);
4353 check_added_monitors!(nodes[1], 1);
4354 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4356 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4357 mine_transaction(&nodes[1], &node_txn[0]);
4358 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4360 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4361 assert_eq!(spend_txn.len(), 3);
4362 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4363 check_spends!(spend_txn[1], node_txn[0]);
4364 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4368 fn test_static_spendable_outputs_preimage_tx() {
4369 let chanmon_cfgs = create_chanmon_cfgs(2);
4370 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4371 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4372 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4374 // Create some initial channels
4375 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4377 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4379 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4380 assert_eq!(commitment_tx[0].input.len(), 1);
4381 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4383 // Settle A's commitment tx on B's chain
4384 nodes[1].node.claim_funds(payment_preimage);
4385 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4386 check_added_monitors!(nodes[1], 1);
4387 mine_transaction(&nodes[1], &commitment_tx[0]);
4388 check_added_monitors!(nodes[1], 1);
4389 let events = nodes[1].node.get_and_clear_pending_msg_events();
4391 MessageSendEvent::UpdateHTLCs { .. } => {},
4392 _ => panic!("Unexpected event"),
4395 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4396 _ => panic!("Unexepected event"),
4399 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4400 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4401 assert_eq!(node_txn.len(), 1);
4402 check_spends!(node_txn[0], commitment_tx[0]);
4403 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4405 mine_transaction(&nodes[1], &node_txn[0]);
4406 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4407 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4409 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4410 assert_eq!(spend_txn.len(), 1);
4411 check_spends!(spend_txn[0], node_txn[0]);
4415 fn test_static_spendable_outputs_timeout_tx() {
4416 let chanmon_cfgs = create_chanmon_cfgs(2);
4417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4419 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4421 // Create some initial channels
4422 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4424 // Rebalance the network a bit by relaying one payment through all the channels ...
4425 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4427 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4429 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4430 assert_eq!(commitment_tx[0].input.len(), 1);
4431 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4433 // Settle A's commitment tx on B' chain
4434 mine_transaction(&nodes[1], &commitment_tx[0]);
4435 check_added_monitors!(nodes[1], 1);
4436 let events = nodes[1].node.get_and_clear_pending_msg_events();
4438 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4439 _ => panic!("Unexpected event"),
4441 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4443 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4444 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4445 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4446 check_spends!(node_txn[0], commitment_tx[0].clone());
4447 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4449 mine_transaction(&nodes[1], &node_txn[0]);
4450 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4451 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4452 expect_payment_failed!(nodes[1], our_payment_hash, false);
4454 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4455 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4456 check_spends!(spend_txn[0], commitment_tx[0]);
4457 check_spends!(spend_txn[1], node_txn[0]);
4458 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4462 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4463 let chanmon_cfgs = create_chanmon_cfgs(2);
4464 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4465 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4466 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4468 // Create some initial channels
4469 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4471 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4472 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4473 assert_eq!(revoked_local_txn[0].input.len(), 1);
4474 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4476 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4478 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4479 check_closed_broadcast!(nodes[1], true);
4480 check_added_monitors!(nodes[1], 1);
4481 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4483 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4484 assert_eq!(node_txn.len(), 1);
4485 assert_eq!(node_txn[0].input.len(), 2);
4486 check_spends!(node_txn[0], revoked_local_txn[0]);
4488 mine_transaction(&nodes[1], &node_txn[0]);
4489 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4491 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4492 assert_eq!(spend_txn.len(), 1);
4493 check_spends!(spend_txn[0], node_txn[0]);
4497 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4498 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4499 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4502 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4504 // Create some initial channels
4505 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4507 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4508 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4509 assert_eq!(revoked_local_txn[0].input.len(), 1);
4510 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4512 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4514 // A will generate HTLC-Timeout from revoked commitment tx
4515 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4516 check_closed_broadcast!(nodes[0], true);
4517 check_added_monitors!(nodes[0], 1);
4518 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4519 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4521 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4522 assert_eq!(revoked_htlc_txn.len(), 1);
4523 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4524 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4525 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4526 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4528 // B will generate justice tx from A's revoked commitment/HTLC tx
4529 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4530 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4531 check_closed_broadcast!(nodes[1], true);
4532 check_added_monitors!(nodes[1], 1);
4533 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4535 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4536 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4537 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4538 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4539 // transactions next...
4540 assert_eq!(node_txn[0].input.len(), 3);
4541 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4543 assert_eq!(node_txn[1].input.len(), 2);
4544 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4545 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4546 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4548 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4549 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4552 mine_transaction(&nodes[1], &node_txn[1]);
4553 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4555 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4556 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4557 assert_eq!(spend_txn.len(), 1);
4558 assert_eq!(spend_txn[0].input.len(), 1);
4559 check_spends!(spend_txn[0], node_txn[1]);
4563 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4564 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4565 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4568 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4570 // Create some initial channels
4571 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4573 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4574 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4575 assert_eq!(revoked_local_txn[0].input.len(), 1);
4576 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4578 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4579 assert_eq!(revoked_local_txn[0].output.len(), 2);
4581 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4583 // B will generate HTLC-Success from revoked commitment tx
4584 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4585 check_closed_broadcast!(nodes[1], true);
4586 check_added_monitors!(nodes[1], 1);
4587 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4588 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4590 assert_eq!(revoked_htlc_txn.len(), 1);
4591 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4592 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4593 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4595 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4596 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4597 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4599 // A will generate justice tx from B's revoked commitment/HTLC tx
4600 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
4601 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4602 check_closed_broadcast!(nodes[0], true);
4603 check_added_monitors!(nodes[0], 1);
4604 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4606 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4607 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4609 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4610 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4611 // transactions next...
4612 assert_eq!(node_txn[0].input.len(), 2);
4613 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4614 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4615 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4617 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4618 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4621 assert_eq!(node_txn[1].input.len(), 1);
4622 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4624 mine_transaction(&nodes[0], &node_txn[1]);
4625 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4627 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4628 // didn't try to generate any new transactions.
4630 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4631 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4632 assert_eq!(spend_txn.len(), 3);
4633 assert_eq!(spend_txn[0].input.len(), 1);
4634 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4635 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4636 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4637 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4641 fn test_onchain_to_onchain_claim() {
4642 // Test that in case of channel closure, we detect the state of output and claim HTLC
4643 // on downstream peer's remote commitment tx.
4644 // First, have C claim an HTLC against its own latest commitment transaction.
4645 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4647 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4650 let chanmon_cfgs = create_chanmon_cfgs(3);
4651 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4652 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4653 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4655 // Create some initial channels
4656 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4657 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4659 // Ensure all nodes are at the same height
4660 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4661 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4662 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4663 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4665 // Rebalance the network a bit by relaying one payment through all the channels ...
4666 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4667 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4669 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4670 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4671 check_spends!(commitment_tx[0], chan_2.3);
4672 nodes[2].node.claim_funds(payment_preimage);
4673 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4674 check_added_monitors!(nodes[2], 1);
4675 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4676 assert!(updates.update_add_htlcs.is_empty());
4677 assert!(updates.update_fail_htlcs.is_empty());
4678 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4679 assert!(updates.update_fail_malformed_htlcs.is_empty());
4681 mine_transaction(&nodes[2], &commitment_tx[0]);
4682 check_closed_broadcast!(nodes[2], true);
4683 check_added_monitors!(nodes[2], 1);
4684 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4686 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4687 assert_eq!(c_txn.len(), 1);
4688 check_spends!(c_txn[0], commitment_tx[0]);
4689 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4690 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4691 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4693 // 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
4694 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
4695 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone(), c_txn[0].clone()]});
4696 check_added_monitors!(nodes[1], 1);
4697 let events = nodes[1].node.get_and_clear_pending_events();
4698 assert_eq!(events.len(), 2);
4700 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4701 _ => panic!("Unexpected event"),
4704 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4705 assert_eq!(fee_earned_msat, Some(1000));
4706 assert_eq!(prev_channel_id, Some(chan_1.2));
4707 assert_eq!(claim_from_onchain_tx, true);
4708 assert_eq!(next_channel_id, Some(chan_2.2));
4709 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4711 _ => panic!("Unexpected event"),
4713 check_added_monitors!(nodes[1], 1);
4714 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4715 assert_eq!(msg_events.len(), 3);
4716 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4717 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4719 match nodes_2_event {
4720 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4721 _ => panic!("Unexpected event"),
4724 match nodes_0_event {
4725 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, .. } } => {
4726 assert!(update_add_htlcs.is_empty());
4727 assert!(update_fail_htlcs.is_empty());
4728 assert_eq!(update_fulfill_htlcs.len(), 1);
4729 assert!(update_fail_malformed_htlcs.is_empty());
4730 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4732 _ => panic!("Unexpected event"),
4735 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4736 match msg_events[0] {
4737 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4738 _ => panic!("Unexpected event"),
4741 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4742 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4743 mine_transaction(&nodes[1], &commitment_tx[0]);
4744 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4745 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4746 // ChannelMonitor: HTLC-Success tx
4747 assert_eq!(b_txn.len(), 1);
4748 check_spends!(b_txn[0], commitment_tx[0]);
4749 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4750 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4751 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx
4753 check_closed_broadcast!(nodes[1], true);
4754 check_added_monitors!(nodes[1], 1);
4758 fn test_duplicate_payment_hash_one_failure_one_success() {
4759 // Topology : A --> B --> C --> D
4760 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4761 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4762 // we forward one of the payments onwards to D.
4763 let chanmon_cfgs = create_chanmon_cfgs(4);
4764 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4765 // When this test was written, the default base fee floated based on the HTLC count.
4766 // It is now fixed, so we simply set the fee to the expected value here.
4767 let mut config = test_default_channel_config();
4768 config.channel_config.forwarding_fee_base_msat = 196;
4769 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4770 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4771 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4773 create_announced_chan_between_nodes(&nodes, 0, 1);
4774 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4775 create_announced_chan_between_nodes(&nodes, 2, 3);
4777 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4778 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4779 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4780 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4781 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4783 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4785 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4786 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4787 // script push size limit so that the below script length checks match
4788 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4789 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4790 .with_features(nodes[3].node.invoice_features());
4791 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000, TEST_FINAL_CLTV - 40);
4792 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4794 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4795 assert_eq!(commitment_txn[0].input.len(), 1);
4796 check_spends!(commitment_txn[0], chan_2.3);
4798 mine_transaction(&nodes[1], &commitment_txn[0]);
4799 check_closed_broadcast!(nodes[1], true);
4800 check_added_monitors!(nodes[1], 1);
4801 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4802 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
4804 let htlc_timeout_tx;
4805 { // Extract one of the two HTLC-Timeout transaction
4806 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4807 // ChannelMonitor: timeout tx * 2-or-3
4808 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4810 check_spends!(node_txn[0], commitment_txn[0]);
4811 assert_eq!(node_txn[0].input.len(), 1);
4812 assert_eq!(node_txn[0].output.len(), 1);
4814 if node_txn.len() > 2 {
4815 check_spends!(node_txn[1], commitment_txn[0]);
4816 assert_eq!(node_txn[1].input.len(), 1);
4817 assert_eq!(node_txn[1].output.len(), 1);
4818 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4820 check_spends!(node_txn[2], commitment_txn[0]);
4821 assert_eq!(node_txn[2].input.len(), 1);
4822 assert_eq!(node_txn[2].output.len(), 1);
4823 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4825 check_spends!(node_txn[1], commitment_txn[0]);
4826 assert_eq!(node_txn[1].input.len(), 1);
4827 assert_eq!(node_txn[1].output.len(), 1);
4828 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4831 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4832 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4834 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4835 if node_txn.len() > 2 {
4836 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4837 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4839 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4843 nodes[2].node.claim_funds(our_payment_preimage);
4844 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4846 mine_transaction(&nodes[2], &commitment_txn[0]);
4847 check_added_monitors!(nodes[2], 2);
4848 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4849 let events = nodes[2].node.get_and_clear_pending_msg_events();
4851 MessageSendEvent::UpdateHTLCs { .. } => {},
4852 _ => panic!("Unexpected event"),
4855 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4856 _ => panic!("Unexepected event"),
4858 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4859 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4860 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4861 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4862 assert_eq!(htlc_success_txn[0].input.len(), 1);
4863 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4864 assert_eq!(htlc_success_txn[1].input.len(), 1);
4865 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4866 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4867 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4869 mine_transaction(&nodes[1], &htlc_timeout_tx);
4870 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4871 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 }]);
4872 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4873 assert!(htlc_updates.update_add_htlcs.is_empty());
4874 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4875 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4876 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4877 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4878 check_added_monitors!(nodes[1], 1);
4880 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4881 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4883 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4885 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4887 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4888 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4889 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4890 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4891 assert!(updates.update_add_htlcs.is_empty());
4892 assert!(updates.update_fail_htlcs.is_empty());
4893 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4894 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4895 assert!(updates.update_fail_malformed_htlcs.is_empty());
4896 check_added_monitors!(nodes[1], 1);
4898 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4899 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4900 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4904 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4905 let chanmon_cfgs = create_chanmon_cfgs(2);
4906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4908 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4910 // Create some initial channels
4911 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4913 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4914 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4915 assert_eq!(local_txn.len(), 1);
4916 assert_eq!(local_txn[0].input.len(), 1);
4917 check_spends!(local_txn[0], chan_1.3);
4919 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4920 nodes[1].node.claim_funds(payment_preimage);
4921 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4922 check_added_monitors!(nodes[1], 1);
4924 mine_transaction(&nodes[1], &local_txn[0]);
4925 check_added_monitors!(nodes[1], 1);
4926 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4927 let events = nodes[1].node.get_and_clear_pending_msg_events();
4929 MessageSendEvent::UpdateHTLCs { .. } => {},
4930 _ => panic!("Unexpected event"),
4933 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4934 _ => panic!("Unexepected event"),
4937 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4938 assert_eq!(node_txn.len(), 1);
4939 assert_eq!(node_txn[0].input.len(), 1);
4940 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4941 check_spends!(node_txn[0], local_txn[0]);
4945 mine_transaction(&nodes[1], &node_tx);
4946 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4948 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4949 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4950 assert_eq!(spend_txn.len(), 1);
4951 assert_eq!(spend_txn[0].input.len(), 1);
4952 check_spends!(spend_txn[0], node_tx);
4953 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4956 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4957 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4958 // unrevoked commitment transaction.
4959 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4960 // a remote RAA before they could be failed backwards (and combinations thereof).
4961 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4962 // use the same payment hashes.
4963 // Thus, we use a six-node network:
4968 // And test where C fails back to A/B when D announces its latest commitment transaction
4969 let chanmon_cfgs = create_chanmon_cfgs(6);
4970 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4971 // When this test was written, the default base fee floated based on the HTLC count.
4972 // It is now fixed, so we simply set the fee to the expected value here.
4973 let mut config = test_default_channel_config();
4974 config.channel_config.forwarding_fee_base_msat = 196;
4975 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4976 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4977 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4979 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4980 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4981 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4982 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4983 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4985 // Rebalance and check output sanity...
4986 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4987 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4988 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4990 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4991 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4993 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
4995 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
4996 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4998 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
5000 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
5002 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5004 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5005 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5007 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());
5009 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());
5012 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5014 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5015 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
5018 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
5020 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5021 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());
5023 // Double-check that six of the new HTLC were added
5024 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5025 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5026 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5027 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5029 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5030 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5031 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5032 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5033 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5034 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5035 check_added_monitors!(nodes[4], 0);
5037 let failed_destinations = vec![
5038 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5039 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5040 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5041 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5043 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5044 check_added_monitors!(nodes[4], 1);
5046 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5047 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5048 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5049 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5050 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5051 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5053 // Fail 3rd below-dust and 7th above-dust HTLCs
5054 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5055 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5056 check_added_monitors!(nodes[5], 0);
5058 let failed_destinations_2 = vec![
5059 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5060 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5062 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5063 check_added_monitors!(nodes[5], 1);
5065 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5066 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5067 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5068 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5070 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5072 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5073 let failed_destinations_3 = vec![
5074 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5075 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
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[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5079 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5081 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5082 check_added_monitors!(nodes[3], 1);
5083 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5084 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5085 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5086 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5087 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5088 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5089 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5090 if deliver_last_raa {
5091 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5093 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5096 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5097 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5098 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5099 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5101 // We now broadcast the latest commitment transaction, which *should* result in failures for
5102 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5103 // the non-broadcast above-dust HTLCs.
5105 // Alternatively, we may broadcast the previous commitment transaction, which should only
5106 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5107 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5109 if announce_latest {
5110 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5112 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5114 let events = nodes[2].node.get_and_clear_pending_events();
5115 let close_event = if deliver_last_raa {
5116 assert_eq!(events.len(), 2 + 6);
5117 events.last().clone().unwrap()
5119 assert_eq!(events.len(), 1);
5120 events.last().clone().unwrap()
5123 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5124 _ => panic!("Unexpected event"),
5127 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5128 check_closed_broadcast!(nodes[2], true);
5129 if deliver_last_raa {
5130 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5132 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();
5133 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5135 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5136 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5138 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5141 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5143 check_added_monitors!(nodes[2], 3);
5145 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5146 assert_eq!(cs_msgs.len(), 2);
5147 let mut a_done = false;
5148 for msg in cs_msgs {
5150 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5151 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5152 // should be failed-backwards here.
5153 let target = if *node_id == nodes[0].node.get_our_node_id() {
5154 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5155 for htlc in &updates.update_fail_htlcs {
5156 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 });
5158 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5163 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5164 for htlc in &updates.update_fail_htlcs {
5165 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5167 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5168 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5171 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5172 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5174 if announce_latest {
5175 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5176 if *node_id == nodes[0].node.get_our_node_id() {
5177 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5180 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5182 _ => panic!("Unexpected event"),
5186 let as_events = nodes[0].node.get_and_clear_pending_events();
5187 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5188 let mut as_failds = HashSet::new();
5189 let mut as_updates = 0;
5190 for event in as_events.iter() {
5191 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5192 assert!(as_failds.insert(*payment_hash));
5193 if *payment_hash != payment_hash_2 {
5194 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5196 assert!(!payment_failed_permanently);
5198 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5201 } else if let &Event::PaymentFailed { .. } = event {
5202 } else { panic!("Unexpected event"); }
5204 assert!(as_failds.contains(&payment_hash_1));
5205 assert!(as_failds.contains(&payment_hash_2));
5206 if announce_latest {
5207 assert!(as_failds.contains(&payment_hash_3));
5208 assert!(as_failds.contains(&payment_hash_5));
5210 assert!(as_failds.contains(&payment_hash_6));
5212 let bs_events = nodes[1].node.get_and_clear_pending_events();
5213 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5214 let mut bs_failds = HashSet::new();
5215 let mut bs_updates = 0;
5216 for event in bs_events.iter() {
5217 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5218 assert!(bs_failds.insert(*payment_hash));
5219 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5220 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5222 assert!(!payment_failed_permanently);
5224 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5227 } else if let &Event::PaymentFailed { .. } = event {
5228 } else { panic!("Unexpected event"); }
5230 assert!(bs_failds.contains(&payment_hash_1));
5231 assert!(bs_failds.contains(&payment_hash_2));
5232 if announce_latest {
5233 assert!(bs_failds.contains(&payment_hash_4));
5235 assert!(bs_failds.contains(&payment_hash_5));
5237 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5238 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5239 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5240 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5241 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5242 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5246 fn test_fail_backwards_latest_remote_announce_a() {
5247 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5251 fn test_fail_backwards_latest_remote_announce_b() {
5252 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5256 fn test_fail_backwards_previous_remote_announce() {
5257 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5258 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5259 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5263 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5264 let chanmon_cfgs = create_chanmon_cfgs(2);
5265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5269 // Create some initial channels
5270 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5272 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5273 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5274 assert_eq!(local_txn[0].input.len(), 1);
5275 check_spends!(local_txn[0], chan_1.3);
5277 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5278 mine_transaction(&nodes[0], &local_txn[0]);
5279 check_closed_broadcast!(nodes[0], true);
5280 check_added_monitors!(nodes[0], 1);
5281 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5282 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5284 let htlc_timeout = {
5285 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5286 assert_eq!(node_txn.len(), 1);
5287 assert_eq!(node_txn[0].input.len(), 1);
5288 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5289 check_spends!(node_txn[0], local_txn[0]);
5293 mine_transaction(&nodes[0], &htlc_timeout);
5294 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5295 expect_payment_failed!(nodes[0], our_payment_hash, false);
5297 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5298 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5299 assert_eq!(spend_txn.len(), 3);
5300 check_spends!(spend_txn[0], local_txn[0]);
5301 assert_eq!(spend_txn[1].input.len(), 1);
5302 check_spends!(spend_txn[1], htlc_timeout);
5303 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5304 assert_eq!(spend_txn[2].input.len(), 2);
5305 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5306 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5307 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5311 fn test_key_derivation_params() {
5312 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5313 // manager rotation to test that `channel_keys_id` returned in
5314 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5315 // then derive a `delayed_payment_key`.
5317 let chanmon_cfgs = create_chanmon_cfgs(3);
5319 // We manually create the node configuration to backup the seed.
5320 let seed = [42; 32];
5321 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5322 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);
5323 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5324 let scorer = Mutex::new(test_utils::TestScorer::new());
5325 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5326 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)) };
5327 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5328 node_cfgs.remove(0);
5329 node_cfgs.insert(0, node);
5331 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5332 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5334 // Create some initial channels
5335 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5337 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5338 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5339 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5341 // Ensure all nodes are at the same height
5342 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5343 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5344 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5345 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5347 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5348 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5349 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5350 assert_eq!(local_txn_1[0].input.len(), 1);
5351 check_spends!(local_txn_1[0], chan_1.3);
5353 // We check funding pubkey are unique
5354 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]));
5355 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]));
5356 if from_0_funding_key_0 == from_1_funding_key_0
5357 || from_0_funding_key_0 == from_1_funding_key_1
5358 || from_0_funding_key_1 == from_1_funding_key_0
5359 || from_0_funding_key_1 == from_1_funding_key_1 {
5360 panic!("Funding pubkeys aren't unique");
5363 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5364 mine_transaction(&nodes[0], &local_txn_1[0]);
5365 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5366 check_closed_broadcast!(nodes[0], true);
5367 check_added_monitors!(nodes[0], 1);
5368 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5370 let htlc_timeout = {
5371 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5372 assert_eq!(node_txn.len(), 1);
5373 assert_eq!(node_txn[0].input.len(), 1);
5374 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5375 check_spends!(node_txn[0], local_txn_1[0]);
5379 mine_transaction(&nodes[0], &htlc_timeout);
5380 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5381 expect_payment_failed!(nodes[0], our_payment_hash, false);
5383 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5384 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5385 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5386 assert_eq!(spend_txn.len(), 3);
5387 check_spends!(spend_txn[0], local_txn_1[0]);
5388 assert_eq!(spend_txn[1].input.len(), 1);
5389 check_spends!(spend_txn[1], htlc_timeout);
5390 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5391 assert_eq!(spend_txn[2].input.len(), 2);
5392 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5393 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5394 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5398 fn test_static_output_closing_tx() {
5399 let chanmon_cfgs = create_chanmon_cfgs(2);
5400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5404 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5406 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5407 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5409 mine_transaction(&nodes[0], &closing_tx);
5410 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5411 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5413 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5414 assert_eq!(spend_txn.len(), 1);
5415 check_spends!(spend_txn[0], closing_tx);
5417 mine_transaction(&nodes[1], &closing_tx);
5418 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5419 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5421 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5422 assert_eq!(spend_txn.len(), 1);
5423 check_spends!(spend_txn[0], closing_tx);
5426 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5427 let chanmon_cfgs = create_chanmon_cfgs(2);
5428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5431 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5433 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5435 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5436 // present in B's local commitment transaction, but none of A's commitment transactions.
5437 nodes[1].node.claim_funds(payment_preimage);
5438 check_added_monitors!(nodes[1], 1);
5439 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5441 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5442 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5443 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5445 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5446 check_added_monitors!(nodes[0], 1);
5447 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5448 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5449 check_added_monitors!(nodes[1], 1);
5451 let starting_block = nodes[1].best_block_info();
5452 let mut block = Block {
5453 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5456 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5457 connect_block(&nodes[1], &block);
5458 block.header.prev_blockhash = block.block_hash();
5460 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5461 check_closed_broadcast!(nodes[1], true);
5462 check_added_monitors!(nodes[1], 1);
5463 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5466 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5467 let chanmon_cfgs = create_chanmon_cfgs(2);
5468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5470 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5471 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5473 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5474 nodes[0].node.send_payment_with_route(&route, payment_hash,
5475 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5476 check_added_monitors!(nodes[0], 1);
5478 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5480 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5481 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5482 // to "time out" the HTLC.
5484 let starting_block = nodes[1].best_block_info();
5485 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
5487 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5488 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5489 header.prev_blockhash = header.block_hash();
5491 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5492 check_closed_broadcast!(nodes[0], true);
5493 check_added_monitors!(nodes[0], 1);
5494 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5497 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5498 let chanmon_cfgs = create_chanmon_cfgs(3);
5499 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5500 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5501 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5502 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5504 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5505 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5506 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5507 // actually revoked.
5508 let htlc_value = if use_dust { 50000 } else { 3000000 };
5509 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5510 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5511 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5512 check_added_monitors!(nodes[1], 1);
5514 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5515 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5516 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5517 check_added_monitors!(nodes[0], 1);
5518 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5519 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5520 check_added_monitors!(nodes[1], 1);
5521 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5522 check_added_monitors!(nodes[1], 1);
5523 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5525 if check_revoke_no_close {
5526 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5527 check_added_monitors!(nodes[0], 1);
5530 let starting_block = nodes[1].best_block_info();
5531 let mut block = Block {
5532 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
5535 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5536 connect_block(&nodes[0], &block);
5537 block.header.prev_blockhash = block.block_hash();
5539 if !check_revoke_no_close {
5540 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5541 check_closed_broadcast!(nodes[0], true);
5542 check_added_monitors!(nodes[0], 1);
5543 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5545 expect_payment_failed!(nodes[0], our_payment_hash, true);
5549 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5550 // There are only a few cases to test here:
5551 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5552 // broadcastable commitment transactions result in channel closure,
5553 // * its included in an unrevoked-but-previous remote commitment transaction,
5554 // * its included in the latest remote or local commitment transactions.
5555 // We test each of the three possible commitment transactions individually and use both dust and
5557 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5558 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5559 // tested for at least one of the cases in other tests.
5561 fn htlc_claim_single_commitment_only_a() {
5562 do_htlc_claim_local_commitment_only(true);
5563 do_htlc_claim_local_commitment_only(false);
5565 do_htlc_claim_current_remote_commitment_only(true);
5566 do_htlc_claim_current_remote_commitment_only(false);
5570 fn htlc_claim_single_commitment_only_b() {
5571 do_htlc_claim_previous_remote_commitment_only(true, false);
5572 do_htlc_claim_previous_remote_commitment_only(false, false);
5573 do_htlc_claim_previous_remote_commitment_only(true, true);
5574 do_htlc_claim_previous_remote_commitment_only(false, true);
5579 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5580 let chanmon_cfgs = create_chanmon_cfgs(2);
5581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5584 // Force duplicate randomness for every get-random call
5585 for node in nodes.iter() {
5586 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5589 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5590 let channel_value_satoshis=10000;
5591 let push_msat=10001;
5592 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5593 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5594 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5595 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5597 // Create a second channel with the same random values. This used to panic due to a colliding
5598 // channel_id, but now panics due to a colliding outbound SCID alias.
5599 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5603 fn bolt2_open_channel_sending_node_checks_part2() {
5604 let chanmon_cfgs = create_chanmon_cfgs(2);
5605 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5607 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5609 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5610 let channel_value_satoshis=2^24;
5611 let push_msat=10001;
5612 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5614 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5615 let channel_value_satoshis=10000;
5616 // Test when push_msat is equal to 1000 * funding_satoshis.
5617 let push_msat=1000*channel_value_satoshis+1;
5618 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5620 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5621 let channel_value_satoshis=10000;
5622 let push_msat=10001;
5623 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
5624 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5625 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5627 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5628 // 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
5629 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5631 // 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.
5632 assert!(BREAKDOWN_TIMEOUT>0);
5633 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5635 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5636 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5637 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5639 // 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.
5640 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5641 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5642 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5643 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5644 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5648 fn bolt2_open_channel_sane_dust_limit() {
5649 let chanmon_cfgs = create_chanmon_cfgs(2);
5650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5652 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5654 let channel_value_satoshis=1000000;
5655 let push_msat=10001;
5656 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5657 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5658 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5659 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5661 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5662 let events = nodes[1].node.get_and_clear_pending_msg_events();
5663 let err_msg = match events[0] {
5664 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5667 _ => panic!("Unexpected event"),
5669 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5672 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5673 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5674 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5675 // is no longer affordable once it's freed.
5677 fn test_fail_holding_cell_htlc_upon_free() {
5678 let chanmon_cfgs = create_chanmon_cfgs(2);
5679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5681 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5682 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5684 // First nodes[0] generates an update_fee, setting the channel's
5685 // pending_update_fee.
5687 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5688 *feerate_lock += 20;
5690 nodes[0].node.timer_tick_occurred();
5691 check_added_monitors!(nodes[0], 1);
5693 let events = nodes[0].node.get_and_clear_pending_msg_events();
5694 assert_eq!(events.len(), 1);
5695 let (update_msg, commitment_signed) = match events[0] {
5696 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5697 (update_fee.as_ref(), commitment_signed)
5699 _ => panic!("Unexpected event"),
5702 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5704 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5705 let channel_reserve = chan_stat.channel_reserve_msat;
5706 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5707 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5709 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5710 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5711 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5713 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5714 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5715 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5716 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5717 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5719 // Flush the pending fee update.
5720 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5721 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5722 check_added_monitors!(nodes[1], 1);
5723 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5724 check_added_monitors!(nodes[0], 1);
5726 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5727 // HTLC, but now that the fee has been raised the payment will now fail, causing
5728 // us to surface its failure to the user.
5729 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5730 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5731 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);
5732 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 {}",
5733 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5734 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5736 // Check that the payment failed to be sent out.
5737 let events = nodes[0].node.get_and_clear_pending_events();
5738 assert_eq!(events.len(), 2);
5740 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5741 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5742 assert_eq!(our_payment_hash.clone(), *payment_hash);
5743 assert_eq!(*payment_failed_permanently, false);
5744 assert_eq!(*short_channel_id, Some(route.paths[0][0].short_channel_id));
5746 _ => panic!("Unexpected event"),
5749 &Event::PaymentFailed { ref payment_hash, .. } => {
5750 assert_eq!(our_payment_hash.clone(), *payment_hash);
5752 _ => panic!("Unexpected event"),
5756 // Test that if multiple HTLCs are released from the holding cell and one is
5757 // valid but the other is no longer valid upon release, the valid HTLC can be
5758 // successfully completed while the other one fails as expected.
5760 fn test_free_and_fail_holding_cell_htlcs() {
5761 let chanmon_cfgs = create_chanmon_cfgs(2);
5762 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5763 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5764 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5765 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5767 // First nodes[0] generates an update_fee, setting the channel's
5768 // pending_update_fee.
5770 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5771 *feerate_lock += 200;
5773 nodes[0].node.timer_tick_occurred();
5774 check_added_monitors!(nodes[0], 1);
5776 let events = nodes[0].node.get_and_clear_pending_msg_events();
5777 assert_eq!(events.len(), 1);
5778 let (update_msg, commitment_signed) = match events[0] {
5779 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5780 (update_fee.as_ref(), commitment_signed)
5782 _ => panic!("Unexpected event"),
5785 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5787 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5788 let channel_reserve = chan_stat.channel_reserve_msat;
5789 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5790 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5792 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5794 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5795 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5796 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5798 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5799 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5800 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5801 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5802 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5803 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5804 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5805 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5806 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5807 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5809 // Flush the pending fee update.
5810 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5811 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5812 check_added_monitors!(nodes[1], 1);
5813 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5814 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5815 check_added_monitors!(nodes[0], 2);
5817 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5818 // but now that the fee has been raised the second payment will now fail, causing us
5819 // to surface its failure to the user. The first payment should succeed.
5820 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5821 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5822 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);
5823 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 {}",
5824 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5825 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5827 // Check that the second payment failed to be sent out.
5828 let events = nodes[0].node.get_and_clear_pending_events();
5829 assert_eq!(events.len(), 2);
5831 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5832 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5833 assert_eq!(payment_hash_2.clone(), *payment_hash);
5834 assert_eq!(*payment_failed_permanently, false);
5835 assert_eq!(*short_channel_id, Some(route_2.paths[0][0].short_channel_id));
5837 _ => panic!("Unexpected event"),
5840 &Event::PaymentFailed { ref payment_hash, .. } => {
5841 assert_eq!(payment_hash_2.clone(), *payment_hash);
5843 _ => panic!("Unexpected event"),
5846 // Complete the first payment and the RAA from the fee update.
5847 let (payment_event, send_raa_event) = {
5848 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5849 assert_eq!(msgs.len(), 2);
5850 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5852 let raa = match send_raa_event {
5853 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5854 _ => panic!("Unexpected event"),
5856 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5857 check_added_monitors!(nodes[1], 1);
5858 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5859 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5860 let events = nodes[1].node.get_and_clear_pending_events();
5861 assert_eq!(events.len(), 1);
5863 Event::PendingHTLCsForwardable { .. } => {},
5864 _ => panic!("Unexpected event"),
5866 nodes[1].node.process_pending_htlc_forwards();
5867 let events = nodes[1].node.get_and_clear_pending_events();
5868 assert_eq!(events.len(), 1);
5870 Event::PaymentClaimable { .. } => {},
5871 _ => panic!("Unexpected event"),
5873 nodes[1].node.claim_funds(payment_preimage_1);
5874 check_added_monitors!(nodes[1], 1);
5875 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5877 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5878 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5879 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5880 expect_payment_sent!(nodes[0], payment_preimage_1);
5883 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5884 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5885 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5888 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5889 let chanmon_cfgs = create_chanmon_cfgs(3);
5890 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5891 // When this test was written, the default base fee floated based on the HTLC count.
5892 // It is now fixed, so we simply set the fee to the expected value here.
5893 let mut config = test_default_channel_config();
5894 config.channel_config.forwarding_fee_base_msat = 196;
5895 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5896 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5897 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5898 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5900 // First nodes[1] generates an update_fee, setting the channel's
5901 // pending_update_fee.
5903 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5904 *feerate_lock += 20;
5906 nodes[1].node.timer_tick_occurred();
5907 check_added_monitors!(nodes[1], 1);
5909 let events = nodes[1].node.get_and_clear_pending_msg_events();
5910 assert_eq!(events.len(), 1);
5911 let (update_msg, commitment_signed) = match events[0] {
5912 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5913 (update_fee.as_ref(), commitment_signed)
5915 _ => panic!("Unexpected event"),
5918 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5920 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5921 let channel_reserve = chan_stat.channel_reserve_msat;
5922 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5923 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5925 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5927 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
5928 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors) - total_routing_fee_msat;
5929 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5930 let payment_event = {
5931 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5932 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5933 check_added_monitors!(nodes[0], 1);
5935 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5936 assert_eq!(events.len(), 1);
5938 SendEvent::from_event(events.remove(0))
5940 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5941 check_added_monitors!(nodes[1], 0);
5942 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5943 expect_pending_htlcs_forwardable!(nodes[1]);
5945 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5946 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5948 // Flush the pending fee update.
5949 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5950 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5951 check_added_monitors!(nodes[2], 1);
5952 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5953 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5954 check_added_monitors!(nodes[1], 2);
5956 // A final RAA message is generated to finalize the fee update.
5957 let events = nodes[1].node.get_and_clear_pending_msg_events();
5958 assert_eq!(events.len(), 1);
5960 let raa_msg = match &events[0] {
5961 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5964 _ => panic!("Unexpected event"),
5967 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5968 check_added_monitors!(nodes[2], 1);
5969 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5971 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5972 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5973 assert_eq!(process_htlc_forwards_event.len(), 2);
5974 match &process_htlc_forwards_event[0] {
5975 &Event::PendingHTLCsForwardable { .. } => {},
5976 _ => panic!("Unexpected event"),
5979 // In response, we call ChannelManager's process_pending_htlc_forwards
5980 nodes[1].node.process_pending_htlc_forwards();
5981 check_added_monitors!(nodes[1], 1);
5983 // This causes the HTLC to be failed backwards.
5984 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5985 assert_eq!(fail_event.len(), 1);
5986 let (fail_msg, commitment_signed) = match &fail_event[0] {
5987 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5988 assert_eq!(updates.update_add_htlcs.len(), 0);
5989 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5990 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5991 assert_eq!(updates.update_fail_htlcs.len(), 1);
5992 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5994 _ => panic!("Unexpected event"),
5997 // Pass the failure messages back to nodes[0].
5998 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5999 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6001 // Complete the HTLC failure+removal process.
6002 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6003 check_added_monitors!(nodes[0], 1);
6004 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6005 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6006 check_added_monitors!(nodes[1], 2);
6007 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6008 assert_eq!(final_raa_event.len(), 1);
6009 let raa = match &final_raa_event[0] {
6010 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6011 _ => panic!("Unexpected event"),
6013 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6014 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6015 check_added_monitors!(nodes[0], 1);
6018 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6019 // 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.
6020 //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.
6023 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6024 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6025 let chanmon_cfgs = create_chanmon_cfgs(2);
6026 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6028 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6029 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6031 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6032 route.paths[0][0].fee_msat = 100;
6034 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6035 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6036 ), true, APIError::ChannelUnavailable { ref err },
6037 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6038 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6039 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6043 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6044 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6045 let chanmon_cfgs = create_chanmon_cfgs(2);
6046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6048 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6049 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6051 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6052 route.paths[0][0].fee_msat = 0;
6053 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6054 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6055 true, APIError::ChannelUnavailable { ref err },
6056 assert_eq!(err, "Cannot send 0-msat HTLC"));
6058 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6059 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6063 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6064 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6065 let chanmon_cfgs = create_chanmon_cfgs(2);
6066 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6067 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6068 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6069 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6071 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6072 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6073 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6074 check_added_monitors!(nodes[0], 1);
6075 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6076 updates.update_add_htlcs[0].amount_msat = 0;
6078 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6079 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6080 check_closed_broadcast!(nodes[1], true).unwrap();
6081 check_added_monitors!(nodes[1], 1);
6082 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6086 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6087 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6088 //It is enforced when constructing a route.
6089 let chanmon_cfgs = create_chanmon_cfgs(2);
6090 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6091 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6092 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6093 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6095 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6096 .with_features(nodes[1].node.invoice_features());
6097 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000, 0);
6098 route.paths[0].last_mut().unwrap().cltv_expiry_delta = 500000001;
6099 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6100 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6101 ), true, APIError::InvalidRoute { ref err },
6102 assert_eq!(err, &"Channel CLTV overflowed?"));
6106 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6107 //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.
6108 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6109 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6110 let chanmon_cfgs = create_chanmon_cfgs(2);
6111 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6112 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6113 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6114 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6115 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6116 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6118 for i in 0..max_accepted_htlcs {
6119 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6120 let payment_event = {
6121 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6122 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6123 check_added_monitors!(nodes[0], 1);
6125 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6126 assert_eq!(events.len(), 1);
6127 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6128 assert_eq!(htlcs[0].htlc_id, i);
6132 SendEvent::from_event(events.remove(0))
6134 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6135 check_added_monitors!(nodes[1], 0);
6136 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6138 expect_pending_htlcs_forwardable!(nodes[1]);
6139 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6141 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6142 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6143 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6144 ), true, APIError::ChannelUnavailable { ref err },
6145 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6147 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6148 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6152 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6153 //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.
6154 let chanmon_cfgs = create_chanmon_cfgs(2);
6155 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6156 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6157 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6158 let channel_value = 100000;
6159 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6160 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6162 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6164 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6165 // Manually create a route over our max in flight (which our router normally automatically
6167 route.paths[0][0].fee_msat = max_in_flight + 1;
6168 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6169 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6170 ), true, APIError::ChannelUnavailable { ref err },
6171 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)));
6173 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6174 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);
6176 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6179 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6181 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6182 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6183 let chanmon_cfgs = create_chanmon_cfgs(2);
6184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6186 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6187 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6188 let htlc_minimum_msat: u64;
6190 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6191 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6192 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6193 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6196 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6197 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6198 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6199 check_added_monitors!(nodes[0], 1);
6200 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6201 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6202 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6203 assert!(nodes[1].node.list_channels().is_empty());
6204 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6205 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()));
6206 check_added_monitors!(nodes[1], 1);
6207 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6211 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6212 //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
6213 let chanmon_cfgs = create_chanmon_cfgs(2);
6214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6216 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6217 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6219 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6220 let channel_reserve = chan_stat.channel_reserve_msat;
6221 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6222 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6223 // The 2* and +1 are for the fee spike reserve.
6224 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6226 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6227 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6228 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6229 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6230 check_added_monitors!(nodes[0], 1);
6231 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6233 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6234 // at this time channel-initiatee receivers are not required to enforce that senders
6235 // respect the fee_spike_reserve.
6236 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6237 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6239 assert!(nodes[1].node.list_channels().is_empty());
6240 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6241 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6242 check_added_monitors!(nodes[1], 1);
6243 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6247 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6248 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6249 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6250 let chanmon_cfgs = create_chanmon_cfgs(2);
6251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6253 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6254 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6256 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6257 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6258 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6259 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6260 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6261 &route.paths[0], 3999999, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6262 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6264 let mut msg = msgs::UpdateAddHTLC {
6268 payment_hash: our_payment_hash,
6269 cltv_expiry: htlc_cltv,
6270 onion_routing_packet: onion_packet.clone(),
6274 msg.htlc_id = i as u64;
6275 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6277 msg.htlc_id = (50) as u64;
6278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6280 assert!(nodes[1].node.list_channels().is_empty());
6281 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6282 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6283 check_added_monitors!(nodes[1], 1);
6284 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6288 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6289 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6290 let chanmon_cfgs = create_chanmon_cfgs(2);
6291 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6292 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6293 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6294 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6296 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6297 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6298 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6299 check_added_monitors!(nodes[0], 1);
6300 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6301 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;
6302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6304 assert!(nodes[1].node.list_channels().is_empty());
6305 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6306 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6307 check_added_monitors!(nodes[1], 1);
6308 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6312 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6313 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6314 let chanmon_cfgs = create_chanmon_cfgs(2);
6315 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6316 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6317 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6320 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6321 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6322 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6323 check_added_monitors!(nodes[0], 1);
6324 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6325 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6326 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6328 assert!(nodes[1].node.list_channels().is_empty());
6329 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6330 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6331 check_added_monitors!(nodes[1], 1);
6332 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6336 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6337 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6338 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6339 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6340 let chanmon_cfgs = create_chanmon_cfgs(2);
6341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6343 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6345 create_announced_chan_between_nodes(&nodes, 0, 1);
6346 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6347 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6348 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6349 check_added_monitors!(nodes[0], 1);
6350 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6351 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6353 //Disconnect and Reconnect
6354 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6355 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6356 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();
6357 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6358 assert_eq!(reestablish_1.len(), 1);
6359 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();
6360 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6361 assert_eq!(reestablish_2.len(), 1);
6362 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6363 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6364 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6365 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6368 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6369 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6370 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6371 check_added_monitors!(nodes[1], 1);
6372 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6376 assert!(nodes[1].node.list_channels().is_empty());
6377 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6378 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6379 check_added_monitors!(nodes[1], 1);
6380 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6384 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6385 //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.
6387 let chanmon_cfgs = create_chanmon_cfgs(2);
6388 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6389 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6390 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6391 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6392 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6393 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6394 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6396 check_added_monitors!(nodes[0], 1);
6397 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6398 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6400 let update_msg = msgs::UpdateFulfillHTLC{
6403 payment_preimage: our_payment_preimage,
6406 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6408 assert!(nodes[0].node.list_channels().is_empty());
6409 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6410 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()));
6411 check_added_monitors!(nodes[0], 1);
6412 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6416 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6417 //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.
6419 let chanmon_cfgs = create_chanmon_cfgs(2);
6420 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6421 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6422 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6423 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6425 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6426 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6427 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6428 check_added_monitors!(nodes[0], 1);
6429 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6430 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6432 let update_msg = msgs::UpdateFailHTLC{
6435 reason: msgs::OnionErrorPacket { data: Vec::new()},
6438 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6440 assert!(nodes[0].node.list_channels().is_empty());
6441 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6442 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()));
6443 check_added_monitors!(nodes[0], 1);
6444 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6448 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6449 //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.
6451 let chanmon_cfgs = create_chanmon_cfgs(2);
6452 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6453 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6454 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6455 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6457 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6458 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6459 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6460 check_added_monitors!(nodes[0], 1);
6461 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6463 let update_msg = msgs::UpdateFailMalformedHTLC{
6466 sha256_of_onion: [1; 32],
6467 failure_code: 0x8000,
6470 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6472 assert!(nodes[0].node.list_channels().is_empty());
6473 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6474 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()));
6475 check_added_monitors!(nodes[0], 1);
6476 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6480 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6481 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6483 let chanmon_cfgs = create_chanmon_cfgs(2);
6484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6486 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6487 create_announced_chan_between_nodes(&nodes, 0, 1);
6489 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6491 nodes[1].node.claim_funds(our_payment_preimage);
6492 check_added_monitors!(nodes[1], 1);
6493 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6495 let events = nodes[1].node.get_and_clear_pending_msg_events();
6496 assert_eq!(events.len(), 1);
6497 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6499 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, .. } } => {
6500 assert!(update_add_htlcs.is_empty());
6501 assert_eq!(update_fulfill_htlcs.len(), 1);
6502 assert!(update_fail_htlcs.is_empty());
6503 assert!(update_fail_malformed_htlcs.is_empty());
6504 assert!(update_fee.is_none());
6505 update_fulfill_htlcs[0].clone()
6507 _ => panic!("Unexpected event"),
6511 update_fulfill_msg.htlc_id = 1;
6513 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6515 assert!(nodes[0].node.list_channels().is_empty());
6516 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6517 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6518 check_added_monitors!(nodes[0], 1);
6519 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6523 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6524 //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.
6526 let chanmon_cfgs = create_chanmon_cfgs(2);
6527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530 create_announced_chan_between_nodes(&nodes, 0, 1);
6532 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6534 nodes[1].node.claim_funds(our_payment_preimage);
6535 check_added_monitors!(nodes[1], 1);
6536 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6538 let events = nodes[1].node.get_and_clear_pending_msg_events();
6539 assert_eq!(events.len(), 1);
6540 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6542 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, .. } } => {
6543 assert!(update_add_htlcs.is_empty());
6544 assert_eq!(update_fulfill_htlcs.len(), 1);
6545 assert!(update_fail_htlcs.is_empty());
6546 assert!(update_fail_malformed_htlcs.is_empty());
6547 assert!(update_fee.is_none());
6548 update_fulfill_htlcs[0].clone()
6550 _ => panic!("Unexpected event"),
6554 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6556 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6558 assert!(nodes[0].node.list_channels().is_empty());
6559 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6560 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6561 check_added_monitors!(nodes[0], 1);
6562 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6566 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6567 //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.
6569 let chanmon_cfgs = create_chanmon_cfgs(2);
6570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6575 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6576 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6577 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6578 check_added_monitors!(nodes[0], 1);
6580 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6581 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6583 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6584 check_added_monitors!(nodes[1], 0);
6585 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6587 let events = nodes[1].node.get_and_clear_pending_msg_events();
6589 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6591 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, .. } } => {
6592 assert!(update_add_htlcs.is_empty());
6593 assert!(update_fulfill_htlcs.is_empty());
6594 assert!(update_fail_htlcs.is_empty());
6595 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6596 assert!(update_fee.is_none());
6597 update_fail_malformed_htlcs[0].clone()
6599 _ => panic!("Unexpected event"),
6602 update_msg.failure_code &= !0x8000;
6603 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6605 assert!(nodes[0].node.list_channels().is_empty());
6606 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6607 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6608 check_added_monitors!(nodes[0], 1);
6609 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6613 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6614 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6615 // * 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.
6617 let chanmon_cfgs = create_chanmon_cfgs(3);
6618 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6620 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6621 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6622 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6624 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6627 let mut payment_event = {
6628 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6629 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6630 check_added_monitors!(nodes[0], 1);
6631 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6632 assert_eq!(events.len(), 1);
6633 SendEvent::from_event(events.remove(0))
6635 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6636 check_added_monitors!(nodes[1], 0);
6637 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6638 expect_pending_htlcs_forwardable!(nodes[1]);
6639 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6640 assert_eq!(events_2.len(), 1);
6641 check_added_monitors!(nodes[1], 1);
6642 payment_event = SendEvent::from_event(events_2.remove(0));
6643 assert_eq!(payment_event.msgs.len(), 1);
6646 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6647 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6648 check_added_monitors!(nodes[2], 0);
6649 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6651 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6652 assert_eq!(events_3.len(), 1);
6653 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6655 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 } } => {
6656 assert!(update_add_htlcs.is_empty());
6657 assert!(update_fulfill_htlcs.is_empty());
6658 assert!(update_fail_htlcs.is_empty());
6659 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6660 assert!(update_fee.is_none());
6661 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6663 _ => panic!("Unexpected event"),
6667 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6669 check_added_monitors!(nodes[1], 0);
6670 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6671 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 }]);
6672 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6673 assert_eq!(events_4.len(), 1);
6675 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6677 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, .. } } => {
6678 assert!(update_add_htlcs.is_empty());
6679 assert!(update_fulfill_htlcs.is_empty());
6680 assert_eq!(update_fail_htlcs.len(), 1);
6681 assert!(update_fail_malformed_htlcs.is_empty());
6682 assert!(update_fee.is_none());
6684 _ => panic!("Unexpected event"),
6687 check_added_monitors!(nodes[1], 1);
6691 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6692 let chanmon_cfgs = create_chanmon_cfgs(3);
6693 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6694 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6695 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6696 create_announced_chan_between_nodes(&nodes, 0, 1);
6697 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6699 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6702 let mut payment_event = {
6703 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6704 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6705 check_added_monitors!(nodes[0], 1);
6706 SendEvent::from_node(&nodes[0])
6709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6710 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6711 expect_pending_htlcs_forwardable!(nodes[1]);
6712 check_added_monitors!(nodes[1], 1);
6713 payment_event = SendEvent::from_node(&nodes[1]);
6714 assert_eq!(payment_event.msgs.len(), 1);
6717 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6718 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6719 check_added_monitors!(nodes[2], 0);
6720 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6722 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6723 assert_eq!(events_3.len(), 1);
6725 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6726 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6727 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6728 update_msg.failure_code |= 0x2000;
6730 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6731 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6733 _ => panic!("Unexpected event"),
6736 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6737 vec![HTLCDestination::NextHopChannel {
6738 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6739 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6740 assert_eq!(events_4.len(), 1);
6741 check_added_monitors!(nodes[1], 1);
6744 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6745 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6746 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6748 _ => panic!("Unexpected event"),
6751 let events_5 = nodes[0].node.get_and_clear_pending_events();
6752 assert_eq!(events_5.len(), 2);
6754 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6755 // the node originating the error to its next hop.
6757 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6759 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6760 assert!(is_permanent);
6761 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6763 _ => panic!("Unexpected event"),
6766 Event::PaymentFailed { payment_hash, .. } => {
6767 assert_eq!(payment_hash, our_payment_hash);
6769 _ => panic!("Unexpected event"),
6772 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6775 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6776 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6777 // 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
6778 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6780 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6781 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6784 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6785 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6787 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6788 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6790 // We route 2 dust-HTLCs between A and B
6791 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6792 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6793 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6795 // Cache one local commitment tx as previous
6796 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6798 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6799 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6800 check_added_monitors!(nodes[1], 0);
6801 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6802 check_added_monitors!(nodes[1], 1);
6804 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6805 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6806 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6807 check_added_monitors!(nodes[0], 1);
6809 // Cache one local commitment tx as lastest
6810 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6812 let events = nodes[0].node.get_and_clear_pending_msg_events();
6814 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6815 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6817 _ => panic!("Unexpected event"),
6820 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6821 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6823 _ => panic!("Unexpected event"),
6826 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6827 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6828 if announce_latest {
6829 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6831 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6834 check_closed_broadcast!(nodes[0], true);
6835 check_added_monitors!(nodes[0], 1);
6836 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6838 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6839 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6840 let events = nodes[0].node.get_and_clear_pending_events();
6841 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6842 assert_eq!(events.len(), 4);
6843 let mut first_failed = false;
6844 for event in events {
6846 Event::PaymentPathFailed { payment_hash, .. } => {
6847 if payment_hash == payment_hash_1 {
6848 assert!(!first_failed);
6849 first_failed = true;
6851 assert_eq!(payment_hash, payment_hash_2);
6854 Event::PaymentFailed { .. } => {}
6855 _ => panic!("Unexpected event"),
6861 fn test_failure_delay_dust_htlc_local_commitment() {
6862 do_test_failure_delay_dust_htlc_local_commitment(true);
6863 do_test_failure_delay_dust_htlc_local_commitment(false);
6866 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6867 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6868 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6869 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6870 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6871 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6872 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6874 let chanmon_cfgs = create_chanmon_cfgs(3);
6875 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6876 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6877 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6878 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6880 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6881 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6883 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6884 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6886 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6887 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6889 // We revoked bs_commitment_tx
6891 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6892 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6895 let mut timeout_tx = Vec::new();
6897 // We fail dust-HTLC 1 by broadcast of local commitment tx
6898 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6899 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6900 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6901 expect_payment_failed!(nodes[0], dust_hash, false);
6903 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6904 check_closed_broadcast!(nodes[0], true);
6905 check_added_monitors!(nodes[0], 1);
6906 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6907 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6908 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6909 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6910 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6911 mine_transaction(&nodes[0], &timeout_tx[0]);
6912 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6913 expect_payment_failed!(nodes[0], non_dust_hash, false);
6915 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6916 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6917 check_closed_broadcast!(nodes[0], true);
6918 check_added_monitors!(nodes[0], 1);
6919 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6920 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6922 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6923 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6924 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6925 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6926 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6927 // dust HTLC should have been failed.
6928 expect_payment_failed!(nodes[0], dust_hash, false);
6931 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6933 assert_eq!(timeout_tx[0].lock_time.0, 12);
6935 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6936 mine_transaction(&nodes[0], &timeout_tx[0]);
6937 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6938 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6939 expect_payment_failed!(nodes[0], non_dust_hash, false);
6944 fn test_sweep_outbound_htlc_failure_update() {
6945 do_test_sweep_outbound_htlc_failure_update(false, true);
6946 do_test_sweep_outbound_htlc_failure_update(false, false);
6947 do_test_sweep_outbound_htlc_failure_update(true, false);
6951 fn test_user_configurable_csv_delay() {
6952 // We test our channel constructors yield errors when we pass them absurd csv delay
6954 let mut low_our_to_self_config = UserConfig::default();
6955 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6956 let mut high_their_to_self_config = UserConfig::default();
6957 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6958 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6959 let chanmon_cfgs = create_chanmon_cfgs(2);
6960 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6961 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6962 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6964 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6965 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6966 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6967 &low_our_to_self_config, 0, 42)
6970 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())); },
6971 _ => panic!("Unexpected event"),
6973 } else { assert!(false) }
6975 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6976 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6977 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6978 open_channel.to_self_delay = 200;
6979 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6980 &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,
6981 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6984 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())); },
6985 _ => panic!("Unexpected event"),
6987 } else { assert!(false); }
6989 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6990 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6991 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()));
6992 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6993 accept_channel.to_self_delay = 200;
6994 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6996 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6998 &ErrorAction::SendErrorMessage { ref msg } => {
6999 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()));
7000 reason_msg = msg.data.clone();
7004 } else { panic!(); }
7005 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7007 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7008 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7009 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7010 open_channel.to_self_delay = 200;
7011 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7012 &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,
7013 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7016 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())); },
7017 _ => panic!("Unexpected event"),
7019 } else { assert!(false); }
7023 fn test_check_htlc_underpaying() {
7024 // Send payment through A -> B but A is maliciously
7025 // sending a probe payment (i.e less than expected value0
7026 // to B, B should refuse payment.
7028 let chanmon_cfgs = create_chanmon_cfgs(2);
7029 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7030 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7031 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7033 // Create some initial channels
7034 create_announced_chan_between_nodes(&nodes, 0, 1);
7036 let scorer = test_utils::TestScorer::new();
7037 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7038 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV).with_features(nodes[1].node.invoice_features());
7039 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();
7040 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7041 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7042 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7043 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7044 check_added_monitors!(nodes[0], 1);
7046 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7047 assert_eq!(events.len(), 1);
7048 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7049 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7050 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7052 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7053 // and then will wait a second random delay before failing the HTLC back:
7054 expect_pending_htlcs_forwardable!(nodes[1]);
7055 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7057 // Node 3 is expecting payment of 100_000 but received 10_000,
7058 // it should fail htlc like we didn't know the preimage.
7059 nodes[1].node.process_pending_htlc_forwards();
7061 let events = nodes[1].node.get_and_clear_pending_msg_events();
7062 assert_eq!(events.len(), 1);
7063 let (update_fail_htlc, commitment_signed) = match events[0] {
7064 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 } } => {
7065 assert!(update_add_htlcs.is_empty());
7066 assert!(update_fulfill_htlcs.is_empty());
7067 assert_eq!(update_fail_htlcs.len(), 1);
7068 assert!(update_fail_malformed_htlcs.is_empty());
7069 assert!(update_fee.is_none());
7070 (update_fail_htlcs[0].clone(), commitment_signed)
7072 _ => panic!("Unexpected event"),
7074 check_added_monitors!(nodes[1], 1);
7076 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7077 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7079 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7080 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7081 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7082 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7086 fn test_announce_disable_channels() {
7087 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7088 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7090 let chanmon_cfgs = create_chanmon_cfgs(2);
7091 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7092 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7093 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7095 create_announced_chan_between_nodes(&nodes, 0, 1);
7096 create_announced_chan_between_nodes(&nodes, 1, 0);
7097 create_announced_chan_between_nodes(&nodes, 0, 1);
7100 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7101 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7103 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7104 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7105 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7106 assert_eq!(msg_events.len(), 3);
7107 let mut chans_disabled = HashMap::new();
7108 for e in msg_events {
7110 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7111 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7112 // Check that each channel gets updated exactly once
7113 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7114 panic!("Generated ChannelUpdate for wrong chan!");
7117 _ => panic!("Unexpected event"),
7121 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();
7122 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7123 assert_eq!(reestablish_1.len(), 3);
7124 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();
7125 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7126 assert_eq!(reestablish_2.len(), 3);
7128 // Reestablish chan_1
7129 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7130 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7131 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7132 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7133 // Reestablish chan_2
7134 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7135 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7136 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7137 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7138 // Reestablish chan_3
7139 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7140 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7141 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7142 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7144 nodes[0].node.timer_tick_occurred();
7145 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7146 nodes[0].node.timer_tick_occurred();
7147 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7148 assert_eq!(msg_events.len(), 3);
7149 for e in msg_events {
7151 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7152 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7153 match chans_disabled.remove(&msg.contents.short_channel_id) {
7154 // Each update should have a higher timestamp than the previous one, replacing
7156 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7157 None => panic!("Generated ChannelUpdate for wrong chan!"),
7160 _ => panic!("Unexpected event"),
7163 // Check that each channel gets updated exactly once
7164 assert!(chans_disabled.is_empty());
7168 fn test_bump_penalty_txn_on_revoked_commitment() {
7169 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7170 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7172 let chanmon_cfgs = create_chanmon_cfgs(2);
7173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7177 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7179 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7180 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7181 .with_features(nodes[0].node.invoice_features());
7182 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000, 30);
7183 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7185 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7186 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7187 assert_eq!(revoked_txn[0].output.len(), 4);
7188 assert_eq!(revoked_txn[0].input.len(), 1);
7189 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7190 let revoked_txid = revoked_txn[0].txid();
7192 let mut penalty_sum = 0;
7193 for outp in revoked_txn[0].output.iter() {
7194 if outp.script_pubkey.is_v0_p2wsh() {
7195 penalty_sum += outp.value;
7199 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7200 let header_114 = connect_blocks(&nodes[1], 14);
7202 // Actually revoke tx by claiming a HTLC
7203 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7204 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7205 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7206 check_added_monitors!(nodes[1], 1);
7208 // One or more justice tx should have been broadcast, check it
7212 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7213 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7214 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7215 assert_eq!(node_txn[0].output.len(), 1);
7216 check_spends!(node_txn[0], revoked_txn[0]);
7217 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7218 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7219 penalty_1 = node_txn[0].txid();
7223 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7224 connect_blocks(&nodes[1], 15);
7225 let mut penalty_2 = penalty_1;
7226 let mut feerate_2 = 0;
7228 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7229 assert_eq!(node_txn.len(), 1);
7230 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7231 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7232 assert_eq!(node_txn[0].output.len(), 1);
7233 check_spends!(node_txn[0], revoked_txn[0]);
7234 penalty_2 = node_txn[0].txid();
7235 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7236 assert_ne!(penalty_2, penalty_1);
7237 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7238 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7239 // Verify 25% bump heuristic
7240 assert!(feerate_2 * 100 >= feerate_1 * 125);
7244 assert_ne!(feerate_2, 0);
7246 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7247 connect_blocks(&nodes[1], 1);
7249 let mut feerate_3 = 0;
7251 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7252 assert_eq!(node_txn.len(), 1);
7253 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7254 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7255 assert_eq!(node_txn[0].output.len(), 1);
7256 check_spends!(node_txn[0], revoked_txn[0]);
7257 penalty_3 = node_txn[0].txid();
7258 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7259 assert_ne!(penalty_3, penalty_2);
7260 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7261 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7262 // Verify 25% bump heuristic
7263 assert!(feerate_3 * 100 >= feerate_2 * 125);
7267 assert_ne!(feerate_3, 0);
7269 nodes[1].node.get_and_clear_pending_events();
7270 nodes[1].node.get_and_clear_pending_msg_events();
7274 fn test_bump_penalty_txn_on_revoked_htlcs() {
7275 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7276 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7278 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7279 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7280 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7281 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7282 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7284 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7285 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7286 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_features(nodes[1].node.invoice_features());
7287 let scorer = test_utils::TestScorer::new();
7288 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7289 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7290 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7291 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7292 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_features(nodes[0].node.invoice_features());
7293 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7294 3_000_000, 50, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
7295 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7297 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7298 assert_eq!(revoked_local_txn[0].input.len(), 1);
7299 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7301 // Revoke local commitment tx
7302 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7304 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7305 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7306 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7307 check_closed_broadcast!(nodes[1], true);
7308 check_added_monitors!(nodes[1], 1);
7309 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7310 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7312 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
7313 assert_eq!(revoked_htlc_txn.len(), 2);
7315 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7316 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7317 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7319 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7320 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7321 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7322 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7324 // Broadcast set of revoked txn on A
7325 let hash_128 = connect_blocks(&nodes[0], 40);
7326 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7327 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7328 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7329 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7330 let events = nodes[0].node.get_and_clear_pending_events();
7331 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7332 match events.last().unwrap() {
7333 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7334 _ => panic!("Unexpected event"),
7340 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7341 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7342 // Verify claim tx are spending revoked HTLC txn
7344 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7345 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7346 // which are included in the same block (they are broadcasted because we scan the
7347 // transactions linearly and generate claims as we go, they likely should be removed in the
7349 assert_eq!(node_txn[0].input.len(), 1);
7350 check_spends!(node_txn[0], revoked_local_txn[0]);
7351 assert_eq!(node_txn[1].input.len(), 1);
7352 check_spends!(node_txn[1], revoked_local_txn[0]);
7353 assert_eq!(node_txn[2].input.len(), 1);
7354 check_spends!(node_txn[2], revoked_local_txn[0]);
7356 // Each of the three justice transactions claim a separate (single) output of the three
7357 // available, which we check here:
7358 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7359 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7360 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7362 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7363 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7365 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7366 // output, checked above).
7367 assert_eq!(node_txn[3].input.len(), 2);
7368 assert_eq!(node_txn[3].output.len(), 1);
7369 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7371 first = node_txn[3].txid();
7372 // Store both feerates for later comparison
7373 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7374 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7375 penalty_txn = vec![node_txn[2].clone()];
7379 // Connect one more block to see if bumped penalty are issued for HTLC txn
7380 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7381 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7382 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7383 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7385 // Few more blocks to confirm penalty txn
7386 connect_blocks(&nodes[0], 4);
7387 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7388 let header_144 = connect_blocks(&nodes[0], 9);
7390 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7391 assert_eq!(node_txn.len(), 1);
7393 assert_eq!(node_txn[0].input.len(), 2);
7394 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7395 // Verify bumped tx is different and 25% bump heuristic
7396 assert_ne!(first, node_txn[0].txid());
7397 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7398 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7399 assert!(feerate_2 * 100 > feerate_1 * 125);
7400 let txn = vec![node_txn[0].clone()];
7404 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7405 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7406 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7407 connect_blocks(&nodes[0], 20);
7409 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7410 // We verify than no new transaction has been broadcast because previously
7411 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7412 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7413 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7414 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7415 // up bumped justice generation.
7416 assert_eq!(node_txn.len(), 0);
7419 check_closed_broadcast!(nodes[0], true);
7420 check_added_monitors!(nodes[0], 1);
7424 fn test_bump_penalty_txn_on_remote_commitment() {
7425 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7426 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7429 // Provide preimage for one
7430 // Check aggregation
7432 let chanmon_cfgs = create_chanmon_cfgs(2);
7433 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7434 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7435 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7437 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7438 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7439 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7441 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7442 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7443 assert_eq!(remote_txn[0].output.len(), 4);
7444 assert_eq!(remote_txn[0].input.len(), 1);
7445 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7447 // Claim a HTLC without revocation (provide B monitor with preimage)
7448 nodes[1].node.claim_funds(payment_preimage);
7449 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7450 mine_transaction(&nodes[1], &remote_txn[0]);
7451 check_added_monitors!(nodes[1], 2);
7452 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7454 // One or more claim tx should have been broadcast, check it
7458 let feerate_timeout;
7459 let feerate_preimage;
7461 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7462 // 3 transactions including:
7463 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7464 assert_eq!(node_txn.len(), 3);
7465 assert_eq!(node_txn[0].input.len(), 1);
7466 assert_eq!(node_txn[1].input.len(), 1);
7467 assert_eq!(node_txn[2].input.len(), 1);
7468 check_spends!(node_txn[0], remote_txn[0]);
7469 check_spends!(node_txn[1], remote_txn[0]);
7470 check_spends!(node_txn[2], remote_txn[0]);
7472 preimage = node_txn[0].txid();
7473 let index = node_txn[0].input[0].previous_output.vout;
7474 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7475 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7477 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7478 (node_txn[2].clone(), node_txn[1].clone())
7480 (node_txn[1].clone(), node_txn[2].clone())
7483 preimage_bump = preimage_bump_tx;
7484 check_spends!(preimage_bump, remote_txn[0]);
7485 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7487 timeout = timeout_tx.txid();
7488 let index = timeout_tx.input[0].previous_output.vout;
7489 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7490 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7494 assert_ne!(feerate_timeout, 0);
7495 assert_ne!(feerate_preimage, 0);
7497 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7498 connect_blocks(&nodes[1], 15);
7500 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7501 assert_eq!(node_txn.len(), 1);
7502 assert_eq!(node_txn[0].input.len(), 1);
7503 assert_eq!(preimage_bump.input.len(), 1);
7504 check_spends!(node_txn[0], remote_txn[0]);
7505 check_spends!(preimage_bump, remote_txn[0]);
7507 let index = preimage_bump.input[0].previous_output.vout;
7508 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7509 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7510 assert!(new_feerate * 100 > feerate_timeout * 125);
7511 assert_ne!(timeout, preimage_bump.txid());
7513 let index = node_txn[0].input[0].previous_output.vout;
7514 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7515 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7516 assert!(new_feerate * 100 > feerate_preimage * 125);
7517 assert_ne!(preimage, node_txn[0].txid());
7522 nodes[1].node.get_and_clear_pending_events();
7523 nodes[1].node.get_and_clear_pending_msg_events();
7527 fn test_counterparty_raa_skip_no_crash() {
7528 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7529 // commitment transaction, we would have happily carried on and provided them the next
7530 // commitment transaction based on one RAA forward. This would probably eventually have led to
7531 // channel closure, but it would not have resulted in funds loss. Still, our
7532 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7533 // check simply that the channel is closed in response to such an RAA, but don't check whether
7534 // we decide to punish our counterparty for revoking their funds (as we don't currently
7536 let chanmon_cfgs = create_chanmon_cfgs(2);
7537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7539 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7540 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7542 let per_commitment_secret;
7543 let next_per_commitment_point;
7545 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7546 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7547 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7549 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7551 // Make signer believe we got a counterparty signature, so that it allows the revocation
7552 keys.get_enforcement_state().last_holder_commitment -= 1;
7553 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7555 // Must revoke without gaps
7556 keys.get_enforcement_state().last_holder_commitment -= 1;
7557 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7559 keys.get_enforcement_state().last_holder_commitment -= 1;
7560 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7561 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7564 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7565 &msgs::RevokeAndACK {
7567 per_commitment_secret,
7568 next_per_commitment_point,
7570 next_local_nonce: None,
7572 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7573 check_added_monitors!(nodes[1], 1);
7574 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7578 fn test_bump_txn_sanitize_tracking_maps() {
7579 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7580 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7582 let chanmon_cfgs = create_chanmon_cfgs(2);
7583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7585 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7587 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7588 // Lock HTLC in both directions
7589 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7590 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7592 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7593 assert_eq!(revoked_local_txn[0].input.len(), 1);
7594 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7596 // Revoke local commitment tx
7597 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7599 // Broadcast set of revoked txn on A
7600 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7601 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7602 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7604 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7605 check_closed_broadcast!(nodes[0], true);
7606 check_added_monitors!(nodes[0], 1);
7607 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7609 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7610 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7611 check_spends!(node_txn[0], revoked_local_txn[0]);
7612 check_spends!(node_txn[1], revoked_local_txn[0]);
7613 check_spends!(node_txn[2], revoked_local_txn[0]);
7614 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7618 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
7619 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7620 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7622 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7623 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7624 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7629 fn test_pending_claimed_htlc_no_balance_underflow() {
7630 // Tests that if we have a pending outbound HTLC as well as a claimed-but-not-fully-removed
7631 // HTLC we will not underflow when we call `Channel::get_balance_msat()`.
7632 let chanmon_cfgs = create_chanmon_cfgs(2);
7633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7636 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
7638 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_010_000);
7639 nodes[1].node.claim_funds(payment_preimage);
7640 expect_payment_claimed!(nodes[1], payment_hash, 1_010_000);
7641 check_added_monitors!(nodes[1], 1);
7642 let fulfill_ev = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7644 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &fulfill_ev.update_fulfill_htlcs[0]);
7645 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
7646 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &fulfill_ev.commitment_signed);
7647 check_added_monitors!(nodes[0], 1);
7648 let (_raa, _cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7650 // At this point nodes[1] has received 1,010k msat (10k msat more than their reserve) and can
7651 // send an HTLC back (though it will go in the holding cell). Send an HTLC back and check we
7652 // can get our balance.
7654 // Get a route from nodes[1] to nodes[0] by getting a route going the other way and then flip
7655 // the public key of the only hop. This works around ChannelDetails not showing the
7656 // almost-claimed HTLC as available balance.
7657 let (mut route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 10_000);
7658 route.payment_params = None; // This is all wrong, but unnecessary
7659 route.paths[0][0].pubkey = nodes[0].node.get_our_node_id();
7660 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[0]);
7661 nodes[1].node.send_payment_with_route(&route, payment_hash_2,
7662 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
7664 assert_eq!(nodes[1].node.list_channels()[0].balance_msat, 1_000_000);
7668 fn test_channel_conf_timeout() {
7669 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7670 // confirm within 2016 blocks, as recommended by BOLT 2.
7671 let chanmon_cfgs = create_chanmon_cfgs(2);
7672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7674 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7676 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7678 // The outbound node should wait forever for confirmation:
7679 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7680 // copied here instead of directly referencing the constant.
7681 connect_blocks(&nodes[0], 2016);
7682 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7684 // The inbound node should fail the channel after exactly 2016 blocks
7685 connect_blocks(&nodes[1], 2015);
7686 check_added_monitors!(nodes[1], 0);
7687 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7689 connect_blocks(&nodes[1], 1);
7690 check_added_monitors!(nodes[1], 1);
7691 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7692 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7693 assert_eq!(close_ev.len(), 1);
7695 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7696 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7697 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7699 _ => panic!("Unexpected event"),
7704 fn test_override_channel_config() {
7705 let chanmon_cfgs = create_chanmon_cfgs(2);
7706 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7707 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7708 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7710 // Node0 initiates a channel to node1 using the override config.
7711 let mut override_config = UserConfig::default();
7712 override_config.channel_handshake_config.our_to_self_delay = 200;
7714 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7716 // Assert the channel created by node0 is using the override config.
7717 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7718 assert_eq!(res.channel_flags, 0);
7719 assert_eq!(res.to_self_delay, 200);
7723 fn test_override_0msat_htlc_minimum() {
7724 let mut zero_config = UserConfig::default();
7725 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7726 let chanmon_cfgs = create_chanmon_cfgs(2);
7727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7731 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7732 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7733 assert_eq!(res.htlc_minimum_msat, 1);
7735 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7736 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7737 assert_eq!(res.htlc_minimum_msat, 1);
7741 fn test_channel_update_has_correct_htlc_maximum_msat() {
7742 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7743 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7744 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7745 // 90% of the `channel_value`.
7746 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7748 let mut config_30_percent = UserConfig::default();
7749 config_30_percent.channel_handshake_config.announced_channel = true;
7750 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7751 let mut config_50_percent = UserConfig::default();
7752 config_50_percent.channel_handshake_config.announced_channel = true;
7753 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7754 let mut config_95_percent = UserConfig::default();
7755 config_95_percent.channel_handshake_config.announced_channel = true;
7756 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7757 let mut config_100_percent = UserConfig::default();
7758 config_100_percent.channel_handshake_config.announced_channel = true;
7759 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7761 let chanmon_cfgs = create_chanmon_cfgs(4);
7762 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7763 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)]);
7764 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7766 let channel_value_satoshis = 100000;
7767 let channel_value_msat = channel_value_satoshis * 1000;
7768 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7769 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7770 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7772 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7773 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7775 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7776 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7777 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7778 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7779 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7780 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7782 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7783 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7785 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7786 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7787 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7789 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7793 fn test_manually_accept_inbound_channel_request() {
7794 let mut manually_accept_conf = UserConfig::default();
7795 manually_accept_conf.manually_accept_inbound_channels = true;
7796 let chanmon_cfgs = create_chanmon_cfgs(2);
7797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7799 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7801 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7802 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7804 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7806 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7807 // accepting the inbound channel request.
7808 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7810 let events = nodes[1].node.get_and_clear_pending_events();
7812 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7813 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7815 _ => panic!("Unexpected event"),
7818 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7819 assert_eq!(accept_msg_ev.len(), 1);
7821 match accept_msg_ev[0] {
7822 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7823 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7825 _ => panic!("Unexpected event"),
7828 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7830 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7831 assert_eq!(close_msg_ev.len(), 1);
7833 let events = nodes[1].node.get_and_clear_pending_events();
7835 Event::ChannelClosed { user_channel_id, .. } => {
7836 assert_eq!(user_channel_id, 23);
7838 _ => panic!("Unexpected event"),
7843 fn test_manually_reject_inbound_channel_request() {
7844 let mut manually_accept_conf = UserConfig::default();
7845 manually_accept_conf.manually_accept_inbound_channels = true;
7846 let chanmon_cfgs = create_chanmon_cfgs(2);
7847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7851 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7852 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7854 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7856 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7857 // rejecting the inbound channel request.
7858 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7860 let events = nodes[1].node.get_and_clear_pending_events();
7862 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7863 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7865 _ => panic!("Unexpected event"),
7868 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7869 assert_eq!(close_msg_ev.len(), 1);
7871 match close_msg_ev[0] {
7872 MessageSendEvent::HandleError { ref node_id, .. } => {
7873 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7875 _ => panic!("Unexpected event"),
7877 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7881 fn test_reject_funding_before_inbound_channel_accepted() {
7882 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7883 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7884 // the node operator before the counterparty sends a `FundingCreated` message. If a
7885 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7886 // and the channel should be closed.
7887 let mut manually_accept_conf = UserConfig::default();
7888 manually_accept_conf.manually_accept_inbound_channels = true;
7889 let chanmon_cfgs = create_chanmon_cfgs(2);
7890 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7891 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7892 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7894 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7895 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7896 let temp_channel_id = res.temporary_channel_id;
7898 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7900 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7901 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7903 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7904 nodes[1].node.get_and_clear_pending_events();
7906 // Get the `AcceptChannel` message of `nodes[1]` without calling
7907 // `ChannelManager::accept_inbound_channel`, which generates a
7908 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7909 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7910 // succeed when `nodes[0]` is passed to it.
7911 let accept_chan_msg = {
7912 let mut node_1_per_peer_lock;
7913 let mut node_1_peer_state_lock;
7914 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7915 channel.get_accept_channel_message()
7917 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7919 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7921 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7922 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7924 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7925 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7927 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7928 assert_eq!(close_msg_ev.len(), 1);
7930 let expected_err = "FundingCreated message received before the channel was accepted";
7931 match close_msg_ev[0] {
7932 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7933 assert_eq!(msg.channel_id, temp_channel_id);
7934 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7935 assert_eq!(msg.data, expected_err);
7937 _ => panic!("Unexpected event"),
7940 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7944 fn test_can_not_accept_inbound_channel_twice() {
7945 let mut manually_accept_conf = UserConfig::default();
7946 manually_accept_conf.manually_accept_inbound_channels = true;
7947 let chanmon_cfgs = create_chanmon_cfgs(2);
7948 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7949 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7950 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7952 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7953 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7955 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7957 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7958 // accepting the inbound channel request.
7959 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7961 let events = nodes[1].node.get_and_clear_pending_events();
7963 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7964 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7965 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7967 Err(APIError::APIMisuseError { err }) => {
7968 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7970 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7971 Err(_) => panic!("Unexpected Error"),
7974 _ => panic!("Unexpected event"),
7977 // Ensure that the channel wasn't closed after attempting to accept it twice.
7978 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7979 assert_eq!(accept_msg_ev.len(), 1);
7981 match accept_msg_ev[0] {
7982 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7983 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7985 _ => panic!("Unexpected event"),
7990 fn test_can_not_accept_unknown_inbound_channel() {
7991 let chanmon_cfg = create_chanmon_cfgs(2);
7992 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7993 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7994 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7996 let unknown_channel_id = [0; 32];
7997 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7999 Err(APIError::ChannelUnavailable { err }) => {
8000 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()));
8002 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8003 Err(_) => panic!("Unexpected Error"),
8008 fn test_onion_value_mpp_set_calculation() {
8009 // Test that we use the onion value `amt_to_forward` when
8010 // calculating whether we've reached the `total_msat` of an MPP
8011 // by having a routing node forward more than `amt_to_forward`
8012 // and checking that the receiving node doesn't generate
8013 // a PaymentClaimable event too early
8015 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8016 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8017 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8018 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8020 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8021 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8022 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8023 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8025 let total_msat = 100_000;
8026 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8027 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8028 let sample_path = route.paths.pop().unwrap();
8030 let mut path_1 = sample_path.clone();
8031 path_1[0].pubkey = nodes[1].node.get_our_node_id();
8032 path_1[0].short_channel_id = chan_1_id;
8033 path_1[1].pubkey = nodes[3].node.get_our_node_id();
8034 path_1[1].short_channel_id = chan_3_id;
8035 path_1[1].fee_msat = 100_000;
8036 route.paths.push(path_1);
8038 let mut path_2 = sample_path.clone();
8039 path_2[0].pubkey = nodes[2].node.get_our_node_id();
8040 path_2[0].short_channel_id = chan_2_id;
8041 path_2[1].pubkey = nodes[3].node.get_our_node_id();
8042 path_2[1].short_channel_id = chan_4_id;
8043 path_2[1].fee_msat = 1_000;
8044 route.paths.push(path_2);
8047 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8048 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8049 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8050 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8051 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8052 check_added_monitors!(nodes[0], expected_paths.len());
8054 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8055 assert_eq!(events.len(), expected_paths.len());
8058 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8059 let mut payment_event = SendEvent::from_event(ev);
8060 let mut prev_node = &nodes[0];
8062 for (idx, &node) in expected_paths[0].iter().enumerate() {
8063 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8065 if idx == 0 { // routing node
8066 let session_priv = [3; 32];
8067 let height = nodes[0].best_block_info().1;
8068 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8069 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8070 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8071 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8072 // Edit amt_to_forward to simulate the sender having set
8073 // the final amount and the routing node taking less fee
8074 onion_payloads[1].amt_to_forward = 99_000;
8075 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
8076 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8079 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8080 check_added_monitors!(node, 0);
8081 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8082 expect_pending_htlcs_forwardable!(node);
8085 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8086 assert_eq!(events_2.len(), 1);
8087 check_added_monitors!(node, 1);
8088 payment_event = SendEvent::from_event(events_2.remove(0));
8089 assert_eq!(payment_event.msgs.len(), 1);
8091 let events_2 = node.node.get_and_clear_pending_events();
8092 assert!(events_2.is_empty());
8099 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8100 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8102 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8105 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8107 let routing_node_count = msat_amounts.len();
8108 let node_count = routing_node_count + 2;
8110 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8111 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8112 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8113 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8118 // Create channels for each amount
8119 let mut expected_paths = Vec::with_capacity(routing_node_count);
8120 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8121 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8122 for i in 0..routing_node_count {
8123 let routing_node = 2 + i;
8124 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8125 src_chan_ids.push(src_chan_id);
8126 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8127 dst_chan_ids.push(dst_chan_id);
8128 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8129 expected_paths.push(path);
8131 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8133 // Create a route for each amount
8134 let example_amount = 100000;
8135 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);
8136 let sample_path = route.paths.pop().unwrap();
8137 for i in 0..routing_node_count {
8138 let routing_node = 2 + i;
8139 let mut path = sample_path.clone();
8140 path[0].pubkey = nodes[routing_node].node.get_our_node_id();
8141 path[0].short_channel_id = src_chan_ids[i];
8142 path[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8143 path[1].short_channel_id = dst_chan_ids[i];
8144 path[1].fee_msat = msat_amounts[i];
8145 route.paths.push(path);
8148 // Send payment with manually set total_msat
8149 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8150 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8151 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8152 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8153 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8154 check_added_monitors!(nodes[src_idx], expected_paths.len());
8156 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8157 assert_eq!(events.len(), expected_paths.len());
8158 let mut amount_received = 0;
8159 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8160 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8162 let current_path_amount = msat_amounts[path_idx];
8163 amount_received += current_path_amount;
8164 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8165 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8168 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8172 fn test_overshoot_mpp() {
8173 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8174 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8178 fn test_simple_mpp() {
8179 // Simple test of sending a multi-path payment.
8180 let chanmon_cfgs = create_chanmon_cfgs(4);
8181 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8182 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8183 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8185 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8186 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8187 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8188 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8190 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8191 let path = route.paths[0].clone();
8192 route.paths.push(path);
8193 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8194 route.paths[0][0].short_channel_id = chan_1_id;
8195 route.paths[0][1].short_channel_id = chan_3_id;
8196 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8197 route.paths[1][0].short_channel_id = chan_2_id;
8198 route.paths[1][1].short_channel_id = chan_4_id;
8199 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8200 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8204 fn test_preimage_storage() {
8205 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8206 let chanmon_cfgs = create_chanmon_cfgs(2);
8207 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8208 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8209 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8211 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8214 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8215 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8216 nodes[0].node.send_payment_with_route(&route, payment_hash,
8217 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8218 check_added_monitors!(nodes[0], 1);
8219 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8220 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8221 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8222 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8224 // Note that after leaving the above scope we have no knowledge of any arguments or return
8225 // values from previous calls.
8226 expect_pending_htlcs_forwardable!(nodes[1]);
8227 let events = nodes[1].node.get_and_clear_pending_events();
8228 assert_eq!(events.len(), 1);
8230 Event::PaymentClaimable { ref purpose, .. } => {
8232 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8233 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8235 _ => panic!("expected PaymentPurpose::InvoicePayment")
8238 _ => panic!("Unexpected event"),
8243 #[allow(deprecated)]
8244 fn test_secret_timeout() {
8245 // Simple test of payment secret storage time outs. After
8246 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8247 let chanmon_cfgs = create_chanmon_cfgs(2);
8248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8250 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8252 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8254 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8256 // We should fail to register the same payment hash twice, at least until we've connected a
8257 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8258 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8259 assert_eq!(err, "Duplicate payment hash");
8260 } else { panic!(); }
8262 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8264 header: BlockHeader {
8266 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8267 merkle_root: TxMerkleNode::all_zeros(),
8268 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8272 connect_block(&nodes[1], &block);
8273 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8274 assert_eq!(err, "Duplicate payment hash");
8275 } else { panic!(); }
8277 // If we then connect the second block, we should be able to register the same payment hash
8278 // again (this time getting a new payment secret).
8279 block.header.prev_blockhash = block.header.block_hash();
8280 block.header.time += 1;
8281 connect_block(&nodes[1], &block);
8282 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8283 assert_ne!(payment_secret_1, our_payment_secret);
8286 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8287 nodes[0].node.send_payment_with_route(&route, payment_hash,
8288 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8289 check_added_monitors!(nodes[0], 1);
8290 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8291 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8292 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8293 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8295 // Note that after leaving the above scope we have no knowledge of any arguments or return
8296 // values from previous calls.
8297 expect_pending_htlcs_forwardable!(nodes[1]);
8298 let events = nodes[1].node.get_and_clear_pending_events();
8299 assert_eq!(events.len(), 1);
8301 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8302 assert!(payment_preimage.is_none());
8303 assert_eq!(payment_secret, our_payment_secret);
8304 // We don't actually have the payment preimage with which to claim this payment!
8306 _ => panic!("Unexpected event"),
8311 fn test_bad_secret_hash() {
8312 // Simple test of unregistered payment hash/invalid payment secret handling
8313 let chanmon_cfgs = create_chanmon_cfgs(2);
8314 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8315 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8316 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8318 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8320 let random_payment_hash = PaymentHash([42; 32]);
8321 let random_payment_secret = PaymentSecret([43; 32]);
8322 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8323 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8325 // All the below cases should end up being handled exactly identically, so we macro the
8326 // resulting events.
8327 macro_rules! handle_unknown_invalid_payment_data {
8328 ($payment_hash: expr) => {
8329 check_added_monitors!(nodes[0], 1);
8330 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8331 let payment_event = SendEvent::from_event(events.pop().unwrap());
8332 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8333 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8335 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8336 // again to process the pending backwards-failure of the HTLC
8337 expect_pending_htlcs_forwardable!(nodes[1]);
8338 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8339 check_added_monitors!(nodes[1], 1);
8341 // We should fail the payment back
8342 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8343 match events.pop().unwrap() {
8344 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8345 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8346 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8348 _ => panic!("Unexpected event"),
8353 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8354 // Error data is the HTLC value (100,000) and current block height
8355 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8357 // Send a payment with the right payment hash but the wrong payment secret
8358 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8359 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8360 handle_unknown_invalid_payment_data!(our_payment_hash);
8361 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8363 // Send a payment with a random payment hash, but the right payment secret
8364 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8365 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8366 handle_unknown_invalid_payment_data!(random_payment_hash);
8367 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8369 // Send a payment with a random payment hash and random payment secret
8370 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8371 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8372 handle_unknown_invalid_payment_data!(random_payment_hash);
8373 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8377 fn test_update_err_monitor_lockdown() {
8378 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8379 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8380 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8383 // This scenario may happen in a watchtower setup, where watchtower process a block height
8384 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8385 // commitment at same time.
8387 let chanmon_cfgs = create_chanmon_cfgs(2);
8388 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8389 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8390 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8392 // Create some initial channel
8393 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8394 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8396 // Rebalance the network to generate htlc in the two directions
8397 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8399 // Route a HTLC from node 0 to node 1 (but don't settle)
8400 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8402 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8403 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8404 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8405 let persister = test_utils::TestPersister::new();
8408 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8409 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8410 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8411 assert!(new_monitor == *monitor);
8414 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);
8415 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8418 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8419 let block = Block { header, txdata: vec![] };
8420 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8421 // transaction lock time requirements here.
8422 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 0));
8423 watchtower.chain_monitor.block_connected(&block, 200);
8425 // Try to update ChannelMonitor
8426 nodes[1].node.claim_funds(preimage);
8427 check_added_monitors!(nodes[1], 1);
8428 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8430 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8431 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8432 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8434 let mut node_0_per_peer_lock;
8435 let mut node_0_peer_state_lock;
8436 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8437 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8438 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8439 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8440 } else { assert!(false); }
8442 // Our local monitor is in-sync and hasn't processed yet timeout
8443 check_added_monitors!(nodes[0], 1);
8444 let events = nodes[0].node.get_and_clear_pending_events();
8445 assert_eq!(events.len(), 1);
8449 fn test_concurrent_monitor_claim() {
8450 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8451 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8452 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8453 // state N+1 confirms. Alice claims output from state N+1.
8455 let chanmon_cfgs = create_chanmon_cfgs(2);
8456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8458 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8460 // Create some initial channel
8461 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8462 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8464 // Rebalance the network to generate htlc in the two directions
8465 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8467 // Route a HTLC from node 0 to node 1 (but don't settle)
8468 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8470 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8471 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8472 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8473 let persister = test_utils::TestPersister::new();
8474 let watchtower_alice = {
8476 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8477 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8478 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8479 assert!(new_monitor == *monitor);
8482 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);
8483 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8486 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8487 let block = Block { header, txdata: vec![] };
8488 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8489 // transaction lock time requirements here.
8490 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));
8491 watchtower_alice.chain_monitor.block_connected(&block, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8493 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8495 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8496 assert_eq!(txn.len(), 2);
8500 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8501 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8502 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8503 let persister = test_utils::TestPersister::new();
8504 let watchtower_bob = {
8506 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8507 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8508 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8509 assert!(new_monitor == *monitor);
8512 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);
8513 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8516 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8517 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8519 // Route another payment to generate another update with still previous HTLC pending
8520 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8521 nodes[1].node.send_payment_with_route(&route, payment_hash,
8522 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8523 check_added_monitors!(nodes[1], 1);
8525 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8526 assert_eq!(updates.update_add_htlcs.len(), 1);
8527 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8529 let mut node_0_per_peer_lock;
8530 let mut node_0_peer_state_lock;
8531 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8532 if let Ok(update) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8533 // Watchtower Alice should already have seen the block and reject the update
8534 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8535 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8536 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8537 } else { assert!(false); }
8539 // Our local monitor is in-sync and hasn't processed yet timeout
8540 check_added_monitors!(nodes[0], 1);
8542 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8543 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8544 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8546 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8549 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8550 assert_eq!(txn.len(), 2);
8551 bob_state_y = txn[0].clone();
8555 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8556 let header = BlockHeader { version: 0x20000000, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8557 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);
8559 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8560 assert_eq!(htlc_txn.len(), 1);
8561 check_spends!(htlc_txn[0], bob_state_y);
8566 fn test_pre_lockin_no_chan_closed_update() {
8567 // Test that if a peer closes a channel in response to a funding_created message we don't
8568 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8571 // Doing so would imply a channel monitor update before the initial channel monitor
8572 // registration, violating our API guarantees.
8574 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8575 // then opening a second channel with the same funding output as the first (which is not
8576 // rejected because the first channel does not exist in the ChannelManager) and closing it
8577 // before receiving funding_signed.
8578 let chanmon_cfgs = create_chanmon_cfgs(2);
8579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8583 // Create an initial channel
8584 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8585 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8586 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8587 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8588 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8590 // Move the first channel through the funding flow...
8591 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8593 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8594 check_added_monitors!(nodes[0], 0);
8596 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8597 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8598 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8599 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8600 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8604 fn test_htlc_no_detection() {
8605 // This test is a mutation to underscore the detection logic bug we had
8606 // before #653. HTLC value routed is above the remaining balance, thus
8607 // inverting HTLC and `to_remote` output. HTLC will come second and
8608 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8609 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8610 // outputs order detection for correct spending children filtring.
8612 let chanmon_cfgs = create_chanmon_cfgs(2);
8613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8617 // Create some initial channels
8618 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8620 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8621 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8622 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8623 assert_eq!(local_txn[0].input.len(), 1);
8624 assert_eq!(local_txn[0].output.len(), 3);
8625 check_spends!(local_txn[0], chan_1.3);
8627 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8628 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8629 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8630 // We deliberately connect the local tx twice as this should provoke a failure calling
8631 // this test before #653 fix.
8632 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);
8633 check_closed_broadcast!(nodes[0], true);
8634 check_added_monitors!(nodes[0], 1);
8635 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8636 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8638 let htlc_timeout = {
8639 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8640 assert_eq!(node_txn.len(), 1);
8641 assert_eq!(node_txn[0].input.len(), 1);
8642 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8643 check_spends!(node_txn[0], local_txn[0]);
8647 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
8648 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8649 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8650 expect_payment_failed!(nodes[0], our_payment_hash, false);
8653 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8654 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8655 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8656 // Carol, Alice would be the upstream node, and Carol the downstream.)
8658 // Steps of the test:
8659 // 1) Alice sends a HTLC to Carol through Bob.
8660 // 2) Carol doesn't settle the HTLC.
8661 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8662 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8663 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8664 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8665 // 5) Carol release the preimage to Bob off-chain.
8666 // 6) Bob claims the offered output on the broadcasted commitment.
8667 let chanmon_cfgs = create_chanmon_cfgs(3);
8668 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8669 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8670 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8672 // Create some initial channels
8673 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8674 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8676 // Steps (1) and (2):
8677 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8678 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8680 // Check that Alice's commitment transaction now contains an output for this HTLC.
8681 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8682 check_spends!(alice_txn[0], chan_ab.3);
8683 assert_eq!(alice_txn[0].output.len(), 2);
8684 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8685 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8686 assert_eq!(alice_txn.len(), 2);
8688 // Steps (3) and (4):
8689 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8690 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8691 let mut force_closing_node = 0; // Alice force-closes
8692 let mut counterparty_node = 1; // Bob if Alice force-closes
8695 if !broadcast_alice {
8696 force_closing_node = 1;
8697 counterparty_node = 0;
8699 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8700 check_closed_broadcast!(nodes[force_closing_node], true);
8701 check_added_monitors!(nodes[force_closing_node], 1);
8702 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8703 if go_onchain_before_fulfill {
8704 let txn_to_broadcast = match broadcast_alice {
8705 true => alice_txn.clone(),
8706 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8708 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8709 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8710 if broadcast_alice {
8711 check_closed_broadcast!(nodes[1], true);
8712 check_added_monitors!(nodes[1], 1);
8713 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8718 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8719 // process of removing the HTLC from their commitment transactions.
8720 nodes[2].node.claim_funds(payment_preimage);
8721 check_added_monitors!(nodes[2], 1);
8722 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8724 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8725 assert!(carol_updates.update_add_htlcs.is_empty());
8726 assert!(carol_updates.update_fail_htlcs.is_empty());
8727 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8728 assert!(carol_updates.update_fee.is_none());
8729 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8731 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8732 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8733 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8734 if !go_onchain_before_fulfill && broadcast_alice {
8735 let events = nodes[1].node.get_and_clear_pending_msg_events();
8736 assert_eq!(events.len(), 1);
8738 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8739 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8741 _ => panic!("Unexpected event"),
8744 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8745 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8746 // Carol<->Bob's updated commitment transaction info.
8747 check_added_monitors!(nodes[1], 2);
8749 let events = nodes[1].node.get_and_clear_pending_msg_events();
8750 assert_eq!(events.len(), 2);
8751 let bob_revocation = match events[0] {
8752 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8753 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8756 _ => panic!("Unexpected event"),
8758 let bob_updates = match events[1] {
8759 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8760 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8763 _ => panic!("Unexpected event"),
8766 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8767 check_added_monitors!(nodes[2], 1);
8768 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8769 check_added_monitors!(nodes[2], 1);
8771 let events = nodes[2].node.get_and_clear_pending_msg_events();
8772 assert_eq!(events.len(), 1);
8773 let carol_revocation = match events[0] {
8774 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8775 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8778 _ => panic!("Unexpected event"),
8780 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8781 check_added_monitors!(nodes[1], 1);
8783 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8784 // here's where we put said channel's commitment tx on-chain.
8785 let mut txn_to_broadcast = alice_txn.clone();
8786 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8787 if !go_onchain_before_fulfill {
8788 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42};
8789 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8790 // If Bob was the one to force-close, he will have already passed these checks earlier.
8791 if broadcast_alice {
8792 check_closed_broadcast!(nodes[1], true);
8793 check_added_monitors!(nodes[1], 1);
8794 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8796 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8797 if broadcast_alice {
8798 assert_eq!(bob_txn.len(), 1);
8799 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8801 assert_eq!(bob_txn.len(), 2);
8802 check_spends!(bob_txn[0], chan_ab.3);
8807 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8808 // broadcasted commitment transaction.
8810 let script_weight = match broadcast_alice {
8811 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8812 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8814 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8815 // Bob force-closed and broadcasts the commitment transaction along with a
8816 // HTLC-output-claiming transaction.
8817 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8818 if broadcast_alice {
8819 assert_eq!(bob_txn.len(), 1);
8820 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8821 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8823 assert_eq!(bob_txn.len(), 2);
8824 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8825 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8831 fn test_onchain_htlc_settlement_after_close() {
8832 do_test_onchain_htlc_settlement_after_close(true, true);
8833 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8834 do_test_onchain_htlc_settlement_after_close(true, false);
8835 do_test_onchain_htlc_settlement_after_close(false, false);
8839 fn test_duplicate_temporary_channel_id_from_different_peers() {
8840 // Tests that we can accept two different `OpenChannel` requests with the same
8841 // `temporary_channel_id`, as long as they are from different peers.
8842 let chanmon_cfgs = create_chanmon_cfgs(3);
8843 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8844 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8845 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8847 // Create an first channel channel
8848 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8849 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8851 // Create an second channel
8852 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8853 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8855 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8856 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8857 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8859 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8860 // `temporary_channel_id` as they are from different peers.
8861 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8863 let events = nodes[0].node.get_and_clear_pending_msg_events();
8864 assert_eq!(events.len(), 1);
8866 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8867 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8868 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8870 _ => panic!("Unexpected event"),
8874 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8876 let events = nodes[0].node.get_and_clear_pending_msg_events();
8877 assert_eq!(events.len(), 1);
8879 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8880 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8881 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8883 _ => panic!("Unexpected event"),
8889 fn test_duplicate_chan_id() {
8890 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8891 // already open we reject it and keep the old channel.
8893 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8894 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8895 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8896 // updating logic for the existing channel.
8897 let chanmon_cfgs = create_chanmon_cfgs(2);
8898 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8899 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8900 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8902 // Create an initial channel
8903 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8904 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8905 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8906 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()));
8908 // Try to create a second channel with the same temporary_channel_id as the first and check
8909 // that it is rejected.
8910 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8912 let events = nodes[1].node.get_and_clear_pending_msg_events();
8913 assert_eq!(events.len(), 1);
8915 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8916 // Technically, at this point, nodes[1] would be justified in thinking both the
8917 // first (valid) and second (invalid) channels are closed, given they both have
8918 // the same non-temporary channel_id. However, currently we do not, so we just
8919 // move forward with it.
8920 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8921 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8923 _ => panic!("Unexpected event"),
8927 // Move the first channel through the funding flow...
8928 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8930 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8931 check_added_monitors!(nodes[0], 0);
8933 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8934 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8936 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8937 assert_eq!(added_monitors.len(), 1);
8938 assert_eq!(added_monitors[0].0, funding_output);
8939 added_monitors.clear();
8941 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8943 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8945 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8946 let channel_id = funding_outpoint.to_channel_id();
8948 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8951 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8952 // Technically this is allowed by the spec, but we don't support it and there's little reason
8953 // to. Still, it shouldn't cause any other issues.
8954 open_chan_msg.temporary_channel_id = channel_id;
8955 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8957 let events = nodes[1].node.get_and_clear_pending_msg_events();
8958 assert_eq!(events.len(), 1);
8960 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8961 // Technically, at this point, nodes[1] would be justified in thinking both
8962 // channels are closed, but currently we do not, so we just move forward with it.
8963 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8964 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8966 _ => panic!("Unexpected event"),
8970 // Now try to create a second channel which has a duplicate funding output.
8971 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8972 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8973 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8974 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()));
8975 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8977 let funding_created = {
8978 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8979 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8980 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8981 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8982 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8983 // channelmanager in a possibly nonsense state instead).
8984 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8985 let logger = test_utils::TestLogger::new();
8986 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8988 check_added_monitors!(nodes[0], 0);
8989 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8990 // At this point we'll look up if the channel_id is present and immediately fail the channel
8991 // without trying to persist the `ChannelMonitor`.
8992 check_added_monitors!(nodes[1], 0);
8994 // ...still, nodes[1] will reject the duplicate channel.
8996 let events = nodes[1].node.get_and_clear_pending_msg_events();
8997 assert_eq!(events.len(), 1);
8999 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9000 // Technically, at this point, nodes[1] would be justified in thinking both
9001 // channels are closed, but currently we do not, so we just move forward with it.
9002 assert_eq!(msg.channel_id, channel_id);
9003 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9005 _ => panic!("Unexpected event"),
9009 // finally, finish creating the original channel and send a payment over it to make sure
9010 // everything is functional.
9011 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9013 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9014 assert_eq!(added_monitors.len(), 1);
9015 assert_eq!(added_monitors[0].0, funding_output);
9016 added_monitors.clear();
9018 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9020 let events_4 = nodes[0].node.get_and_clear_pending_events();
9021 assert_eq!(events_4.len(), 0);
9022 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9023 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9025 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9026 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9027 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9029 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9033 fn test_error_chans_closed() {
9034 // Test that we properly handle error messages, closing appropriate channels.
9036 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9037 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9038 // we can test various edge cases around it to ensure we don't regress.
9039 let chanmon_cfgs = create_chanmon_cfgs(3);
9040 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9041 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9042 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9044 // Create some initial channels
9045 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9046 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9047 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9049 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9050 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9051 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9053 // Closing a channel from a different peer has no effect
9054 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9055 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9057 // Closing one channel doesn't impact others
9058 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9059 check_added_monitors!(nodes[0], 1);
9060 check_closed_broadcast!(nodes[0], false);
9061 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9062 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9063 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9064 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);
9065 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);
9067 // A null channel ID should close all channels
9068 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9069 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9070 check_added_monitors!(nodes[0], 2);
9071 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9072 let events = nodes[0].node.get_and_clear_pending_msg_events();
9073 assert_eq!(events.len(), 2);
9075 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9076 assert_eq!(msg.contents.flags & 2, 2);
9078 _ => panic!("Unexpected event"),
9081 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9082 assert_eq!(msg.contents.flags & 2, 2);
9084 _ => panic!("Unexpected event"),
9086 // Note that at this point users of a standard PeerHandler will end up calling
9087 // peer_disconnected.
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);
9091 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9092 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9093 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9097 fn test_invalid_funding_tx() {
9098 // Test that we properly handle invalid funding transactions sent to us from a peer.
9100 // Previously, all other major lightning implementations had failed to properly sanitize
9101 // funding transactions from their counterparties, leading to a multi-implementation critical
9102 // security vulnerability (though we always sanitized properly, we've previously had
9103 // un-released crashes in the sanitization process).
9105 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9106 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9107 // gave up on it. We test this here by generating such a transaction.
9108 let chanmon_cfgs = create_chanmon_cfgs(2);
9109 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9110 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9111 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9113 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9114 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()));
9115 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()));
9117 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9119 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9120 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9121 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9123 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9124 let wit_program_script: Script = wit_program.into();
9125 for output in tx.output.iter_mut() {
9126 // Make the confirmed funding transaction have a bogus script_pubkey
9127 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9130 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9131 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()));
9132 check_added_monitors!(nodes[1], 1);
9133 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9135 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()));
9136 check_added_monitors!(nodes[0], 1);
9137 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9139 let events_1 = nodes[0].node.get_and_clear_pending_events();
9140 assert_eq!(events_1.len(), 0);
9142 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9143 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9144 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9146 let expected_err = "funding tx had wrong script/value or output index";
9147 confirm_transaction_at(&nodes[1], &tx, 1);
9148 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9149 check_added_monitors!(nodes[1], 1);
9150 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9151 assert_eq!(events_2.len(), 1);
9152 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9153 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9154 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9155 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9156 } else { panic!(); }
9157 } else { panic!(); }
9158 assert_eq!(nodes[1].node.list_channels().len(), 0);
9160 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9161 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9162 // as its not 32 bytes long.
9163 let mut spend_tx = Transaction {
9164 version: 2i32, lock_time: PackedLockTime::ZERO,
9165 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9166 previous_output: BitcoinOutPoint {
9170 script_sig: Script::new(),
9171 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9172 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9174 output: vec![TxOut {
9176 script_pubkey: Script::new(),
9179 check_spends!(spend_tx, tx);
9180 mine_transaction(&nodes[1], &spend_tx);
9183 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9184 // In the first version of the chain::Confirm interface, after a refactor was made to not
9185 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9186 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9187 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9188 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9189 // spending transaction until height N+1 (or greater). This was due to the way
9190 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9191 // spending transaction at the height the input transaction was confirmed at, not whether we
9192 // should broadcast a spending transaction at the current height.
9193 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9194 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9195 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9196 // until we learned about an additional block.
9198 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9199 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9200 let chanmon_cfgs = create_chanmon_cfgs(3);
9201 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9202 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9203 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9204 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9206 create_announced_chan_between_nodes(&nodes, 0, 1);
9207 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9208 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9209 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9210 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9212 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9213 check_closed_broadcast!(nodes[1], true);
9214 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9215 check_added_monitors!(nodes[1], 1);
9216 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9217 assert_eq!(node_txn.len(), 1);
9219 let conf_height = nodes[1].best_block_info().1;
9220 if !test_height_before_timelock {
9221 connect_blocks(&nodes[1], 24 * 6);
9223 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9224 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9225 if test_height_before_timelock {
9226 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9227 // generate any events or broadcast any transactions
9228 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9229 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9231 // We should broadcast an HTLC transaction spending our funding transaction first
9232 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9233 assert_eq!(spending_txn.len(), 2);
9234 assert_eq!(spending_txn[0], node_txn[0]);
9235 check_spends!(spending_txn[1], node_txn[0]);
9236 // We should also generate a SpendableOutputs event with the to_self output (as its
9238 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9239 assert_eq!(descriptor_spend_txn.len(), 1);
9241 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9242 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9243 // additional block built on top of the current chain.
9244 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9245 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9246 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 }]);
9247 check_added_monitors!(nodes[1], 1);
9249 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9250 assert!(updates.update_add_htlcs.is_empty());
9251 assert!(updates.update_fulfill_htlcs.is_empty());
9252 assert_eq!(updates.update_fail_htlcs.len(), 1);
9253 assert!(updates.update_fail_malformed_htlcs.is_empty());
9254 assert!(updates.update_fee.is_none());
9255 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9256 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9257 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9262 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9263 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9264 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9267 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9268 let chanmon_cfgs = create_chanmon_cfgs(2);
9269 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9270 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9271 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9273 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9275 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9276 .with_features(nodes[1].node.invoice_features());
9277 let route = get_route!(nodes[0], payment_params, 10_000, TEST_FINAL_CLTV).unwrap();
9279 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9282 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9283 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9284 check_added_monitors!(nodes[0], 1);
9285 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9286 assert_eq!(events.len(), 1);
9287 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9288 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9289 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9291 expect_pending_htlcs_forwardable!(nodes[1]);
9292 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9295 // Note that we use a different PaymentId here to allow us to duplicativly pay
9296 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9297 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9298 check_added_monitors!(nodes[0], 1);
9299 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9300 assert_eq!(events.len(), 1);
9301 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9303 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9304 // At this point, nodes[1] would notice it has too much value for the payment. It will
9305 // assume the second is a privacy attack (no longer particularly relevant
9306 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9307 // the first HTLC delivered above.
9310 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9311 nodes[1].node.process_pending_htlc_forwards();
9313 if test_for_second_fail_panic {
9314 // Now we go fail back the first HTLC from the user end.
9315 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9317 let expected_destinations = vec![
9318 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9319 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9321 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9322 nodes[1].node.process_pending_htlc_forwards();
9324 check_added_monitors!(nodes[1], 1);
9325 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9326 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9328 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9329 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9330 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9332 let failure_events = nodes[0].node.get_and_clear_pending_events();
9333 assert_eq!(failure_events.len(), 4);
9334 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9335 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9336 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9337 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9339 // Let the second HTLC fail and claim the first
9340 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9341 nodes[1].node.process_pending_htlc_forwards();
9343 check_added_monitors!(nodes[1], 1);
9344 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9345 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9346 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9348 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9350 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9355 fn test_dup_htlc_second_fail_panic() {
9356 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9357 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9358 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9359 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9360 do_test_dup_htlc_second_rejected(true);
9364 fn test_dup_htlc_second_rejected() {
9365 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9366 // simply reject the second HTLC but are still able to claim the first HTLC.
9367 do_test_dup_htlc_second_rejected(false);
9371 fn test_inconsistent_mpp_params() {
9372 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9373 // such HTLC and allow the second to stay.
9374 let chanmon_cfgs = create_chanmon_cfgs(4);
9375 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9376 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9377 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9379 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9380 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9381 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9382 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9384 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9385 .with_features(nodes[3].node.invoice_features());
9386 let mut route = get_route!(nodes[0], payment_params, 15_000_000, TEST_FINAL_CLTV).unwrap();
9387 assert_eq!(route.paths.len(), 2);
9388 route.paths.sort_by(|path_a, _| {
9389 // Sort the path so that the path through nodes[1] comes first
9390 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9391 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9394 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9396 let cur_height = nodes[0].best_block_info().1;
9397 let payment_id = PaymentId([42; 32]);
9399 let session_privs = {
9400 // We create a fake route here so that we start with three pending HTLCs, which we'll
9401 // ultimately have, just not right away.
9402 let mut dup_route = route.clone();
9403 dup_route.paths.push(route.paths[1].clone());
9404 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9405 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9407 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9408 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9409 &None, session_privs[0]).unwrap();
9410 check_added_monitors!(nodes[0], 1);
9413 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9414 assert_eq!(events.len(), 1);
9415 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9417 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9419 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9420 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9421 check_added_monitors!(nodes[0], 1);
9424 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9425 assert_eq!(events.len(), 1);
9426 let payment_event = SendEvent::from_event(events.pop().unwrap());
9428 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9429 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9431 expect_pending_htlcs_forwardable!(nodes[2]);
9432 check_added_monitors!(nodes[2], 1);
9434 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9435 assert_eq!(events.len(), 1);
9436 let payment_event = SendEvent::from_event(events.pop().unwrap());
9438 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9439 check_added_monitors!(nodes[3], 0);
9440 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9442 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9443 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9444 // post-payment_secrets) and fail back the new HTLC.
9446 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9447 nodes[3].node.process_pending_htlc_forwards();
9448 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9449 nodes[3].node.process_pending_htlc_forwards();
9451 check_added_monitors!(nodes[3], 1);
9453 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9454 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9455 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9457 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 }]);
9458 check_added_monitors!(nodes[2], 1);
9460 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9461 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9462 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9464 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9466 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9467 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9468 &None, session_privs[2]).unwrap();
9469 check_added_monitors!(nodes[0], 1);
9471 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9472 assert_eq!(events.len(), 1);
9473 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9475 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9476 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9480 fn test_keysend_payments_to_public_node() {
9481 let chanmon_cfgs = create_chanmon_cfgs(2);
9482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9484 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9486 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9487 let network_graph = nodes[0].network_graph.clone();
9488 let payer_pubkey = nodes[0].node.get_our_node_id();
9489 let payee_pubkey = nodes[1].node.get_our_node_id();
9490 let route_params = RouteParameters {
9491 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9492 final_value_msat: 10000,
9494 let scorer = test_utils::TestScorer::new();
9495 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9496 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
9498 let test_preimage = PaymentPreimage([42; 32]);
9499 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9500 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9501 check_added_monitors!(nodes[0], 1);
9502 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9503 assert_eq!(events.len(), 1);
9504 let event = events.pop().unwrap();
9505 let path = vec![&nodes[1]];
9506 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9507 claim_payment(&nodes[0], &path, test_preimage);
9511 fn test_keysend_payments_to_private_node() {
9512 let chanmon_cfgs = create_chanmon_cfgs(2);
9513 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9514 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9515 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9517 let payer_pubkey = nodes[0].node.get_our_node_id();
9518 let payee_pubkey = nodes[1].node.get_our_node_id();
9520 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9521 let route_params = RouteParameters {
9522 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9523 final_value_msat: 10000,
9525 let network_graph = nodes[0].network_graph.clone();
9526 let first_hops = nodes[0].node.list_usable_channels();
9527 let scorer = test_utils::TestScorer::new();
9528 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9529 let route = find_route(
9530 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9531 nodes[0].logger, &scorer, &random_seed_bytes
9534 let test_preimage = PaymentPreimage([42; 32]);
9535 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9536 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9537 check_added_monitors!(nodes[0], 1);
9538 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9539 assert_eq!(events.len(), 1);
9540 let event = events.pop().unwrap();
9541 let path = vec![&nodes[1]];
9542 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9543 claim_payment(&nodes[0], &path, test_preimage);
9547 fn test_double_partial_claim() {
9548 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9549 // time out, the sender resends only some of the MPP parts, then the user processes the
9550 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9552 let chanmon_cfgs = create_chanmon_cfgs(4);
9553 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9554 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9555 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9557 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9558 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9559 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9560 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9562 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9563 assert_eq!(route.paths.len(), 2);
9564 route.paths.sort_by(|path_a, _| {
9565 // Sort the path so that the path through nodes[1] comes first
9566 if path_a[0].pubkey == nodes[1].node.get_our_node_id() {
9567 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9570 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9571 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9572 // amount of time to respond to.
9574 // Connect some blocks to time out the payment
9575 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9576 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9578 let failed_destinations = vec![
9579 HTLCDestination::FailedPayment { payment_hash },
9580 HTLCDestination::FailedPayment { payment_hash },
9582 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9584 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9586 // nodes[1] now retries one of the two paths...
9587 nodes[0].node.send_payment_with_route(&route, payment_hash,
9588 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9589 check_added_monitors!(nodes[0], 2);
9591 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9592 assert_eq!(events.len(), 2);
9593 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9594 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9596 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9597 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9598 nodes[3].node.claim_funds(payment_preimage);
9599 check_added_monitors!(nodes[3], 0);
9600 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9603 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9604 #[derive(Clone, Copy, PartialEq)]
9605 enum ExposureEvent {
9606 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9608 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9610 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9611 AtUpdateFeeOutbound,
9614 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9615 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9618 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9619 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9620 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9621 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9622 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9623 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9624 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9625 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9627 let chanmon_cfgs = create_chanmon_cfgs(2);
9628 let mut config = test_default_channel_config();
9629 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9630 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9631 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9632 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9634 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9635 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9636 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9637 open_channel.max_accepted_htlcs = 60;
9639 open_channel.dust_limit_satoshis = 546;
9641 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9642 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9643 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9645 let opt_anchors = false;
9647 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9650 let mut node_0_per_peer_lock;
9651 let mut node_0_peer_state_lock;
9652 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9653 chan.holder_dust_limit_satoshis = 546;
9656 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9657 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()));
9658 check_added_monitors!(nodes[1], 1);
9659 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9661 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()));
9662 check_added_monitors!(nodes[0], 1);
9663 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9665 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9666 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9667 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9669 let dust_buffer_feerate = {
9670 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9671 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9672 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9673 chan.get_dust_buffer_feerate(None) as u64
9675 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;
9676 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9678 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;
9679 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9681 let dust_htlc_on_counterparty_tx: u64 = 25;
9682 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9685 if dust_outbound_balance {
9686 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9687 // Outbound dust balance: 4372 sats
9688 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9689 for _ in 0..dust_outbound_htlc_on_holder_tx {
9690 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9691 nodes[0].node.send_payment_with_route(&route, payment_hash,
9692 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9695 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9696 // Inbound dust balance: 4372 sats
9697 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9698 for _ in 0..dust_inbound_htlc_on_holder_tx {
9699 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9703 if dust_outbound_balance {
9704 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9705 // Outbound dust balance: 5000 sats
9706 for _ in 0..dust_htlc_on_counterparty_tx {
9707 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9708 nodes[0].node.send_payment_with_route(&route, payment_hash,
9709 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9712 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9713 // Inbound dust balance: 5000 sats
9714 for _ in 0..dust_htlc_on_counterparty_tx {
9715 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9720 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9721 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9722 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 });
9723 let mut config = UserConfig::default();
9724 // With default dust exposure: 5000 sats
9726 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9727 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9728 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9729 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9730 ), true, APIError::ChannelUnavailable { ref err },
9731 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)));
9733 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9734 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9735 ), true, APIError::ChannelUnavailable { ref err },
9736 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)));
9738 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9739 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 });
9740 nodes[1].node.send_payment_with_route(&route, payment_hash,
9741 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9742 check_added_monitors!(nodes[1], 1);
9743 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9744 assert_eq!(events.len(), 1);
9745 let payment_event = SendEvent::from_event(events.remove(0));
9746 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9747 // With default dust exposure: 5000 sats
9749 // Outbound dust balance: 6399 sats
9750 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9751 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9752 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);
9754 // Outbound dust balance: 5200 sats
9755 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);
9757 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9758 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9759 nodes[0].node.send_payment_with_route(&route, payment_hash,
9760 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9762 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9763 *feerate_lock = *feerate_lock * 10;
9765 nodes[0].node.timer_tick_occurred();
9766 check_added_monitors!(nodes[0], 1);
9767 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9770 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9771 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9772 added_monitors.clear();
9776 fn test_max_dust_htlc_exposure() {
9777 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9778 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9779 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9780 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9781 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9782 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9783 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9784 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9785 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9786 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9787 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9788 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9792 fn test_non_final_funding_tx() {
9793 let chanmon_cfgs = create_chanmon_cfgs(2);
9794 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9795 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9796 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9798 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9799 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9800 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9801 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9802 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9804 let best_height = nodes[0].node.best_block.read().unwrap().height();
9806 let chan_id = *nodes[0].network_chan_count.borrow();
9807 let events = nodes[0].node.get_and_clear_pending_events();
9808 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9809 assert_eq!(events.len(), 1);
9810 let mut tx = match events[0] {
9811 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9812 // Timelock the transaction _beyond_ the best client height + 2.
9813 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 3), input: vec![input], output: vec![TxOut {
9814 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9817 _ => panic!("Unexpected event"),
9819 // Transaction should fail as it's evaluated as non-final for propagation.
9820 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9821 Err(APIError::APIMisuseError { err }) => {
9822 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9827 // However, transaction should be accepted if it's in a +2 headroom from best block.
9828 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9829 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9830 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9834 fn accept_busted_but_better_fee() {
9835 // If a peer sends us a fee update that is too low, but higher than our previous channel
9836 // feerate, we should accept it. In the future we may want to consider closing the channel
9837 // later, but for now we only accept the update.
9838 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9839 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9840 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9841 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9843 create_chan_between_nodes(&nodes[0], &nodes[1]);
9845 // Set nodes[1] to expect 5,000 sat/kW.
9847 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9848 *feerate_lock = 5000;
9851 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9853 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9854 *feerate_lock = 1000;
9856 nodes[0].node.timer_tick_occurred();
9857 check_added_monitors!(nodes[0], 1);
9859 let events = nodes[0].node.get_and_clear_pending_msg_events();
9860 assert_eq!(events.len(), 1);
9862 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9863 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9864 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9866 _ => panic!("Unexpected event"),
9869 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9872 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9873 *feerate_lock = 2000;
9875 nodes[0].node.timer_tick_occurred();
9876 check_added_monitors!(nodes[0], 1);
9878 let events = nodes[0].node.get_and_clear_pending_msg_events();
9879 assert_eq!(events.len(), 1);
9881 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9882 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9883 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9885 _ => panic!("Unexpected event"),
9888 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9891 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9892 *feerate_lock = 1000;
9894 nodes[0].node.timer_tick_occurred();
9895 check_added_monitors!(nodes[0], 1);
9897 let events = nodes[0].node.get_and_clear_pending_msg_events();
9898 assert_eq!(events.len(), 1);
9900 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9901 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9902 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9903 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9904 check_closed_broadcast!(nodes[1], true);
9905 check_added_monitors!(nodes[1], 1);
9907 _ => panic!("Unexpected event"),
9911 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9912 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9916 let min_final_cltv_expiry_delta = 120;
9917 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9918 min_final_cltv_expiry_delta - 2 };
9919 let recv_value = 100_000;
9921 create_chan_between_nodes(&nodes[0], &nodes[1]);
9923 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9924 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9925 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9926 Some(recv_value), Some(min_final_cltv_expiry_delta));
9927 (payment_hash, payment_preimage, payment_secret)
9929 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9930 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9932 let route = get_route!(nodes[0], payment_parameters, recv_value, final_cltv_expiry_delta as u32).unwrap();
9933 nodes[0].node.send_payment_with_route(&route, payment_hash,
9934 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9935 check_added_monitors!(nodes[0], 1);
9936 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9937 assert_eq!(events.len(), 1);
9938 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9939 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9940 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9941 expect_pending_htlcs_forwardable!(nodes[1]);
9944 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9945 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9947 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9949 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9951 check_added_monitors!(nodes[1], 1);
9953 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9954 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9955 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9957 expect_payment_failed!(nodes[0], payment_hash, true);
9962 fn test_payment_with_custom_min_cltv_expiry_delta() {
9963 do_payment_with_custom_min_final_cltv_expiry(false, false);
9964 do_payment_with_custom_min_final_cltv_expiry(false, true);
9965 do_payment_with_custom_min_final_cltv_expiry(true, false);
9966 do_payment_with_custom_min_final_cltv_expiry(true, true);