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::sign::{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, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, 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::{Path, 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::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
45 use bitcoin::{PackedLockTime, Sequence, Transaction, TxIn, TxOut, Witness};
46 use bitcoin::OutPoint as BitcoinOutPoint;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::{PublicKey,SecretKey};
54 use crate::prelude::*;
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use core::iter::repeat;
58 use bitcoin::hashes::Hash;
59 use crate::sync::{Arc, Mutex};
61 use crate::ln::functional_test_utils::*;
62 use crate::ln::chan_utils::CommitmentTransaction;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
68 let mut cfg = UserConfig::default();
69 cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
70 let chanmon_cfgs = create_chanmon_cfgs(2);
71 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
72 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
73 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
75 // Instantiate channel parameters where we push the maximum msats given our
77 let channel_value_sat = 31337; // same as funding satoshis
78 let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
79 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
81 // Have node0 initiate a channel to node1 with aforementioned parameters
82 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
84 // Extract the channel open message from node0 to node1
85 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
87 // Test helper that asserts we get the correct error string given a mutator
88 // that supposedly makes the channel open message insane
89 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
90 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
91 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
92 assert_eq!(msg_events.len(), 1);
93 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
94 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
96 &ErrorAction::SendErrorMessage { .. } => {
97 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
99 _ => panic!("unexpected event!"),
101 } else { assert!(false); }
104 use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
106 // Test all mutations that would make the channel open message insane
107 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 });
108 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 });
110 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
112 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 });
114 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
116 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 });
118 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 });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_funding_exceeds_no_wumbo_limit() {
127 // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
129 use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
130 let chanmon_cfgs = create_chanmon_cfgs(2);
131 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
132 *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
136 match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None) {
137 Err(APIError::APIMisuseError { err }) => {
138 assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
144 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
145 // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
146 // but only for them. Because some LSPs do it with some level of trust of the clients (for a
147 // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
148 // in normal testing, we test it explicitly here.
149 let chanmon_cfgs = create_chanmon_cfgs(2);
150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
152 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
153 let default_config = UserConfig::default();
155 // Have node0 initiate a channel to node1 with aforementioned parameters
156 let mut push_amt = 100_000_000;
157 let feerate_per_kw = 253;
158 let opt_anchors = false;
159 push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(opt_anchors) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
160 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
162 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();
163 let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
164 if !send_from_initiator {
165 open_channel_message.channel_reserve_satoshis = 0;
166 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
168 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
170 // Extract the channel accept message from node1 to node0
171 let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
172 if send_from_initiator {
173 accept_channel_message.channel_reserve_satoshis = 0;
174 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
176 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
178 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
179 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
180 let mut sender_node_per_peer_lock;
181 let mut sender_node_peer_state_lock;
182 if send_from_initiator {
183 let chan = get_inbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
184 chan.context.holder_selected_channel_reserve_satoshis = 0;
185 chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let chan = get_outbound_v1_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
188 chan.context.holder_selected_channel_reserve_satoshis = 0;
189 chan.context.holder_max_htlc_value_in_flight_msat = 100_000_000;
193 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
194 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
195 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
197 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
198 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
199 if send_from_initiator {
200 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
201 // Note that for outbound channels we have to consider the commitment tx fee and the
202 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
203 // well as an additional HTLC.
204 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
206 send_payment(&nodes[1], &[&nodes[0]], push_amt);
211 fn test_counterparty_no_reserve() {
212 do_test_counterparty_no_reserve(true);
213 do_test_counterparty_no_reserve(false);
217 fn test_async_inbound_update_fee() {
218 let chanmon_cfgs = create_chanmon_cfgs(2);
219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
221 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
222 create_announced_chan_between_nodes(&nodes, 0, 1);
225 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
229 // send (1) commitment_signed -.
230 // <- update_add_htlc/commitment_signed
231 // send (2) RAA (awaiting remote revoke) -.
232 // (1) commitment_signed is delivered ->
233 // .- send (3) RAA (awaiting remote revoke)
234 // (2) RAA is delivered ->
235 // .- send (4) commitment_signed
236 // <- (3) RAA is delivered
237 // send (5) commitment_signed -.
238 // <- (4) commitment_signed is delivered
240 // (5) commitment_signed is delivered ->
242 // (6) RAA is delivered ->
244 // First nodes[0] generates an update_fee
246 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
249 nodes[0].node.timer_tick_occurred();
250 check_added_monitors!(nodes[0], 1);
252 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253 assert_eq!(events_0.len(), 1);
254 let (update_msg, commitment_signed) = match events_0[0] { // (1)
255 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
256 (update_fee.as_ref(), commitment_signed)
258 _ => panic!("Unexpected event"),
261 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
263 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
265 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
266 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
267 check_added_monitors!(nodes[1], 1);
269 let payment_event = {
270 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271 assert_eq!(events_1.len(), 1);
272 SendEvent::from_event(events_1.remove(0))
274 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275 assert_eq!(payment_event.msgs.len(), 1);
277 // ...now when the messages get delivered everyone should be happy
278 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[0], 1);
284 // deliver(1), generate (3):
285 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
286 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
287 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
288 check_added_monitors!(nodes[1], 1);
290 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
291 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
292 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
293 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
294 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
295 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
296 assert!(bs_update.update_fee.is_none()); // (4)
297 check_added_monitors!(nodes[1], 1);
299 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
300 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
301 assert!(as_update.update_add_htlcs.is_empty()); // (5)
302 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
303 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
304 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
305 assert!(as_update.update_fee.is_none()); // (5)
306 check_added_monitors!(nodes[0], 1);
308 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
309 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
310 // only (6) so get_event_msg's assert(len == 1) passes
311 check_added_monitors!(nodes[0], 1);
313 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
314 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
315 check_added_monitors!(nodes[1], 1);
317 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
318 check_added_monitors!(nodes[0], 1);
320 let events_2 = nodes[0].node.get_and_clear_pending_events();
321 assert_eq!(events_2.len(), 1);
323 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
324 _ => panic!("Unexpected event"),
327 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
328 check_added_monitors!(nodes[1], 1);
332 fn test_update_fee_unordered_raa() {
333 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
334 // crash in an earlier version of the update_fee patch)
335 let chanmon_cfgs = create_chanmon_cfgs(2);
336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
339 create_announced_chan_between_nodes(&nodes, 0, 1);
342 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
344 // First nodes[0] generates an update_fee
346 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
349 nodes[0].node.timer_tick_occurred();
350 check_added_monitors!(nodes[0], 1);
352 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
353 assert_eq!(events_0.len(), 1);
354 let update_msg = match events_0[0] { // (1)
355 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
358 _ => panic!("Unexpected event"),
361 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
363 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
364 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
365 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
366 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
367 check_added_monitors!(nodes[1], 1);
369 let payment_event = {
370 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
371 assert_eq!(events_1.len(), 1);
372 SendEvent::from_event(events_1.remove(0))
374 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
375 assert_eq!(payment_event.msgs.len(), 1);
377 // ...now when the messages get delivered everyone should be happy
378 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
379 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
380 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
381 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
382 check_added_monitors!(nodes[0], 1);
384 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
385 check_added_monitors!(nodes[1], 1);
387 // We can't continue, sadly, because our (1) now has a bogus signature
391 fn test_multi_flight_update_fee() {
392 let chanmon_cfgs = create_chanmon_cfgs(2);
393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
395 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
396 create_announced_chan_between_nodes(&nodes, 0, 1);
399 // update_fee/commitment_signed ->
400 // .- send (1) RAA and (2) commitment_signed
401 // update_fee (never committed) ->
403 // We have to manually generate the above update_fee, it is allowed by the protocol but we
404 // don't track which updates correspond to which revoke_and_ack responses so we're in
405 // AwaitingRAA mode and will not generate the update_fee yet.
406 // <- (1) RAA delivered
407 // (3) is generated and send (4) CS -.
408 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
409 // know the per_commitment_point to use for it.
410 // <- (2) commitment_signed delivered
412 // B should send no response here
413 // (4) commitment_signed delivered ->
414 // <- RAA/commitment_signed delivered
417 // First nodes[0] generates an update_fee
420 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
421 initial_feerate = *feerate_lock;
422 *feerate_lock = initial_feerate + 20;
424 nodes[0].node.timer_tick_occurred();
425 check_added_monitors!(nodes[0], 1);
427 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
428 assert_eq!(events_0.len(), 1);
429 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
430 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
431 (update_fee.as_ref().unwrap(), commitment_signed)
433 _ => panic!("Unexpected event"),
436 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
437 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
438 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
439 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
440 check_added_monitors!(nodes[1], 1);
442 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
445 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
446 *feerate_lock = initial_feerate + 40;
448 nodes[0].node.timer_tick_occurred();
449 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
450 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
452 // Create the (3) update_fee message that nodes[0] will generate before it does...
453 let mut update_msg_2 = msgs::UpdateFee {
454 channel_id: update_msg_1.channel_id.clone(),
455 feerate_per_kw: (initial_feerate + 30) as u32,
458 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
460 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
462 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
464 // Deliver (1), generating (3) and (4)
465 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
466 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
467 check_added_monitors!(nodes[0], 1);
468 assert!(as_second_update.update_add_htlcs.is_empty());
469 assert!(as_second_update.update_fulfill_htlcs.is_empty());
470 assert!(as_second_update.update_fail_htlcs.is_empty());
471 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
472 // Check that the update_fee newly generated matches what we delivered:
473 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
474 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
476 // Deliver (2) commitment_signed
477 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
478 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
479 check_added_monitors!(nodes[0], 1);
480 // No commitment_signed so get_event_msg's assert(len == 1) passes
482 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
483 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
484 check_added_monitors!(nodes[1], 1);
487 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
488 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
489 check_added_monitors!(nodes[1], 1);
491 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
492 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
493 check_added_monitors!(nodes[0], 1);
495 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
496 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
497 // No commitment_signed so get_event_msg's assert(len == 1) passes
498 check_added_monitors!(nodes[0], 1);
500 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
501 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
502 check_added_monitors!(nodes[1], 1);
505 fn do_test_sanity_on_in_flight_opens(steps: u8) {
506 // Previously, we had issues deserializing channels when we hadn't connected the first block
507 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
508 // serialization round-trips and simply do steps towards opening a channel and then drop the
511 let chanmon_cfgs = create_chanmon_cfgs(2);
512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
516 if steps & 0b1000_0000 != 0{
517 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
518 connect_block(&nodes[0], &block);
519 connect_block(&nodes[1], &block);
522 if steps & 0x0f == 0 { return; }
523 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
524 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
526 if steps & 0x0f == 1 { return; }
527 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
528 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
530 if steps & 0x0f == 2 { return; }
531 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
533 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
535 if steps & 0x0f == 3 { return; }
536 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
537 check_added_monitors!(nodes[0], 0);
538 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
540 if steps & 0x0f == 4 { return; }
541 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
543 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
544 assert_eq!(added_monitors.len(), 1);
545 assert_eq!(added_monitors[0].0, funding_output);
546 added_monitors.clear();
548 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
550 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
552 if steps & 0x0f == 5 { return; }
553 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
555 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
556 assert_eq!(added_monitors.len(), 1);
557 assert_eq!(added_monitors[0].0, funding_output);
558 added_monitors.clear();
561 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
562 let events_4 = nodes[0].node.get_and_clear_pending_events();
563 assert_eq!(events_4.len(), 0);
565 if steps & 0x0f == 6 { return; }
566 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
568 if steps & 0x0f == 7 { return; }
569 confirm_transaction_at(&nodes[0], &tx, 2);
570 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
571 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
572 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
576 fn test_sanity_on_in_flight_opens() {
577 do_test_sanity_on_in_flight_opens(0);
578 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(1);
580 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(2);
582 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(3);
584 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(4);
586 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(5);
588 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
589 do_test_sanity_on_in_flight_opens(6);
590 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
591 do_test_sanity_on_in_flight_opens(7);
592 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
593 do_test_sanity_on_in_flight_opens(8);
594 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
598 fn test_update_fee_vanilla() {
599 let chanmon_cfgs = create_chanmon_cfgs(2);
600 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
601 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
602 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
603 create_announced_chan_between_nodes(&nodes, 0, 1);
606 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
609 nodes[0].node.timer_tick_occurred();
610 check_added_monitors!(nodes[0], 1);
612 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
613 assert_eq!(events_0.len(), 1);
614 let (update_msg, commitment_signed) = match events_0[0] {
615 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 } } => {
616 (update_fee.as_ref(), commitment_signed)
618 _ => panic!("Unexpected event"),
620 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
622 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
623 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
624 check_added_monitors!(nodes[1], 1);
626 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
627 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
628 check_added_monitors!(nodes[0], 1);
630 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
631 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
632 // No commitment_signed so get_event_msg's assert(len == 1) passes
633 check_added_monitors!(nodes[0], 1);
635 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
636 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
637 check_added_monitors!(nodes[1], 1);
641 fn test_update_fee_that_funder_cannot_afford() {
642 let chanmon_cfgs = create_chanmon_cfgs(2);
643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
645 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
646 let channel_value = 5000;
648 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
649 let channel_id = chan.2;
650 let secp_ctx = Secp256k1::new();
651 let default_config = UserConfig::default();
652 let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
654 let opt_anchors = false;
656 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
657 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
658 // calculate two different feerates here - the expected local limit as well as the expected
660 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;
661 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
663 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
664 *feerate_lock = feerate;
666 nodes[0].node.timer_tick_occurred();
667 check_added_monitors!(nodes[0], 1);
668 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
670 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
672 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
674 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
676 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
678 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
679 assert_eq!(commitment_tx.output.len(), 2);
680 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
681 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
682 actual_fee = channel_value - actual_fee;
683 assert_eq!(total_fee, actual_fee);
687 // Increment the feerate by a small constant, accounting for rounding errors
688 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
691 nodes[0].node.timer_tick_occurred();
692 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
693 check_added_monitors!(nodes[0], 0);
695 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
697 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
698 // needed to sign the new commitment tx and (2) sign the new commitment tx.
699 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
700 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
701 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
702 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
703 let chan_signer = local_chan.get_signer();
704 let pubkeys = chan_signer.pubkeys();
705 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
706 pubkeys.funding_pubkey)
708 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
709 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
710 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
711 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
712 let chan_signer = remote_chan.get_signer();
713 let pubkeys = chan_signer.pubkeys();
714 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
715 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
716 pubkeys.funding_pubkey)
719 // Assemble the set of keys we can use for signatures for our commitment_signed message.
720 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
721 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
724 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
725 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
726 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
727 let local_chan_signer = local_chan.get_signer();
728 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
729 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
730 INITIAL_COMMITMENT_NUMBER - 1,
732 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
733 opt_anchors, local_funding, remote_funding,
734 commit_tx_keys.clone(),
735 non_buffer_feerate + 4,
737 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
739 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
742 let commit_signed_msg = msgs::CommitmentSigned {
745 htlc_signatures: res.1,
747 partial_signature_with_nonce: None,
750 let update_fee = msgs::UpdateFee {
752 feerate_per_kw: non_buffer_feerate + 4,
755 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
757 //While producing the commitment_signed response after handling a received update_fee request the
758 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
759 //Should produce and error.
760 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
761 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
762 check_added_monitors!(nodes[1], 1);
763 check_closed_broadcast!(nodes[1], true);
764 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
768 fn test_update_fee_with_fundee_update_add_htlc() {
769 let chanmon_cfgs = create_chanmon_cfgs(2);
770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
772 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
773 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
776 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
779 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
782 nodes[0].node.timer_tick_occurred();
783 check_added_monitors!(nodes[0], 1);
785 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
786 assert_eq!(events_0.len(), 1);
787 let (update_msg, commitment_signed) = match events_0[0] {
788 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 } } => {
789 (update_fee.as_ref(), commitment_signed)
791 _ => panic!("Unexpected event"),
793 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
794 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
795 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
796 check_added_monitors!(nodes[1], 1);
798 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
800 // nothing happens since node[1] is in AwaitingRemoteRevoke
801 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
802 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
804 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
805 assert_eq!(added_monitors.len(), 0);
806 added_monitors.clear();
808 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
809 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
810 // node[1] has nothing to do
812 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
813 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
814 check_added_monitors!(nodes[0], 1);
816 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
817 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
818 // No commitment_signed so get_event_msg's assert(len == 1) passes
819 check_added_monitors!(nodes[0], 1);
820 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
821 check_added_monitors!(nodes[1], 1);
822 // AwaitingRemoteRevoke ends here
824 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
825 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
826 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
827 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
828 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
829 assert_eq!(commitment_update.update_fee.is_none(), true);
831 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
832 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
833 check_added_monitors!(nodes[0], 1);
834 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
836 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
837 check_added_monitors!(nodes[1], 1);
838 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
840 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
841 check_added_monitors!(nodes[1], 1);
842 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
843 // No commitment_signed so get_event_msg's assert(len == 1) passes
845 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
846 check_added_monitors!(nodes[0], 1);
847 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
849 expect_pending_htlcs_forwardable!(nodes[0]);
851 let events = nodes[0].node.get_and_clear_pending_events();
852 assert_eq!(events.len(), 1);
854 Event::PaymentClaimable { .. } => { },
855 _ => panic!("Unexpected event"),
858 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
860 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
861 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
862 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
863 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
864 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
868 fn test_update_fee() {
869 let chanmon_cfgs = create_chanmon_cfgs(2);
870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
872 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
873 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
874 let channel_id = chan.2;
877 // (1) update_fee/commitment_signed ->
878 // <- (2) revoke_and_ack
879 // .- send (3) commitment_signed
880 // (4) update_fee/commitment_signed ->
881 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
882 // <- (3) commitment_signed delivered
883 // send (6) revoke_and_ack -.
884 // <- (5) deliver revoke_and_ack
885 // (6) deliver revoke_and_ack ->
886 // .- send (7) commitment_signed in response to (4)
887 // <- (7) deliver commitment_signed
890 // Create and deliver (1)...
893 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
894 feerate = *feerate_lock;
895 *feerate_lock = feerate + 20;
897 nodes[0].node.timer_tick_occurred();
898 check_added_monitors!(nodes[0], 1);
900 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
901 assert_eq!(events_0.len(), 1);
902 let (update_msg, commitment_signed) = match events_0[0] {
903 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 } } => {
904 (update_fee.as_ref(), commitment_signed)
906 _ => panic!("Unexpected event"),
908 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
910 // Generate (2) and (3):
911 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
912 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
913 check_added_monitors!(nodes[1], 1);
916 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
917 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
918 check_added_monitors!(nodes[0], 1);
920 // Create and deliver (4)...
922 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
923 *feerate_lock = feerate + 30;
925 nodes[0].node.timer_tick_occurred();
926 check_added_monitors!(nodes[0], 1);
927 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
928 assert_eq!(events_0.len(), 1);
929 let (update_msg, commitment_signed) = match events_0[0] {
930 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 } } => {
931 (update_fee.as_ref(), commitment_signed)
933 _ => panic!("Unexpected event"),
936 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
937 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
938 check_added_monitors!(nodes[1], 1);
940 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
943 // Handle (3), creating (6):
944 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
945 check_added_monitors!(nodes[0], 1);
946 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
947 // No commitment_signed so get_event_msg's assert(len == 1) passes
950 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
951 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
952 check_added_monitors!(nodes[0], 1);
954 // Deliver (6), creating (7):
955 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
956 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
957 assert!(commitment_update.update_add_htlcs.is_empty());
958 assert!(commitment_update.update_fulfill_htlcs.is_empty());
959 assert!(commitment_update.update_fail_htlcs.is_empty());
960 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
961 assert!(commitment_update.update_fee.is_none());
962 check_added_monitors!(nodes[1], 1);
965 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
966 check_added_monitors!(nodes[0], 1);
967 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
968 // No commitment_signed so get_event_msg's assert(len == 1) passes
970 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
971 check_added_monitors!(nodes[1], 1);
972 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
974 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
975 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
976 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
977 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
978 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
982 fn fake_network_test() {
983 // Simple test which builds a network of ChannelManagers, connects them to each other, and
984 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
985 let chanmon_cfgs = create_chanmon_cfgs(4);
986 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
987 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
988 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
990 // Create some initial channels
991 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
992 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
993 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
995 // Rebalance the network a bit by relaying one payment through all the channels...
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);
998 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
999 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1001 // Send some more payments
1002 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1003 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1004 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1006 // Test failure packets
1007 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1008 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1010 // Add a new channel that skips 3
1011 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1013 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1014 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
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);
1018 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1021 // Do some rebalance loop payments, simultaneously
1022 let mut hops = Vec::with_capacity(3);
1023 hops.push(RouteHop {
1024 pubkey: nodes[2].node.get_our_node_id(),
1025 node_features: NodeFeatures::empty(),
1026 short_channel_id: chan_2.0.contents.short_channel_id,
1027 channel_features: ChannelFeatures::empty(),
1029 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1031 hops.push(RouteHop {
1032 pubkey: nodes[3].node.get_our_node_id(),
1033 node_features: NodeFeatures::empty(),
1034 short_channel_id: chan_3.0.contents.short_channel_id,
1035 channel_features: ChannelFeatures::empty(),
1037 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1039 hops.push(RouteHop {
1040 pubkey: nodes[1].node.get_our_node_id(),
1041 node_features: nodes[1].node.node_features(),
1042 short_channel_id: chan_4.0.contents.short_channel_id,
1043 channel_features: nodes[1].node.channel_features(),
1045 cltv_expiry_delta: TEST_FINAL_CLTV,
1047 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;
1048 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;
1049 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1051 let mut hops = Vec::with_capacity(3);
1052 hops.push(RouteHop {
1053 pubkey: nodes[3].node.get_our_node_id(),
1054 node_features: NodeFeatures::empty(),
1055 short_channel_id: chan_4.0.contents.short_channel_id,
1056 channel_features: ChannelFeatures::empty(),
1058 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1060 hops.push(RouteHop {
1061 pubkey: nodes[2].node.get_our_node_id(),
1062 node_features: NodeFeatures::empty(),
1063 short_channel_id: chan_3.0.contents.short_channel_id,
1064 channel_features: ChannelFeatures::empty(),
1066 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1068 hops.push(RouteHop {
1069 pubkey: nodes[1].node.get_our_node_id(),
1070 node_features: nodes[1].node.node_features(),
1071 short_channel_id: chan_2.0.contents.short_channel_id,
1072 channel_features: nodes[1].node.channel_features(),
1074 cltv_expiry_delta: TEST_FINAL_CLTV,
1076 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;
1077 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;
1078 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![Path { hops, blinded_tail: None }], payment_params: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1080 // Claim the rebalances...
1081 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1082 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1084 // Close down the channels...
1085 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1086 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1091 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1092 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1093 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1095 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1096 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1100 fn holding_cell_htlc_counting() {
1101 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1102 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1103 // commitment dance rounds.
1104 let chanmon_cfgs = create_chanmon_cfgs(3);
1105 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1106 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1107 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1108 create_announced_chan_between_nodes(&nodes, 0, 1);
1109 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1111 // Fetch a route in advance as we will be unable to once we're unable to send.
1112 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1114 let mut payments = Vec::new();
1116 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1117 nodes[1].node.send_payment_with_route(&route, payment_hash,
1118 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1119 payments.push((payment_preimage, payment_hash));
1121 check_added_monitors!(nodes[1], 1);
1123 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1124 assert_eq!(events.len(), 1);
1125 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1126 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1128 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1129 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1132 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1133 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1134 ), true, APIError::ChannelUnavailable { .. }, {});
1135 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1138 // This should also be true if we try to forward a payment.
1139 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1141 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1142 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1143 check_added_monitors!(nodes[0], 1);
1146 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1147 assert_eq!(events.len(), 1);
1148 let payment_event = SendEvent::from_event(events.pop().unwrap());
1149 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1151 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1152 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1153 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1154 // fails), the second will process the resulting failure and fail the HTLC backward.
1155 expect_pending_htlcs_forwardable!(nodes[1]);
1156 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 }]);
1157 check_added_monitors!(nodes[1], 1);
1159 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1160 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1161 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1163 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1165 // Now forward all the pending HTLCs and claim them back
1166 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1167 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1168 check_added_monitors!(nodes[2], 1);
1170 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1171 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1172 check_added_monitors!(nodes[1], 1);
1173 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1175 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1176 check_added_monitors!(nodes[1], 1);
1177 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1179 for ref update in as_updates.update_add_htlcs.iter() {
1180 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1182 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1183 check_added_monitors!(nodes[2], 1);
1184 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1185 check_added_monitors!(nodes[2], 1);
1186 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1188 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1189 check_added_monitors!(nodes[1], 1);
1190 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1191 check_added_monitors!(nodes[1], 1);
1192 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1194 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1195 check_added_monitors!(nodes[2], 1);
1197 expect_pending_htlcs_forwardable!(nodes[2]);
1199 let events = nodes[2].node.get_and_clear_pending_events();
1200 assert_eq!(events.len(), payments.len());
1201 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1203 &Event::PaymentClaimable { ref payment_hash, .. } => {
1204 assert_eq!(*payment_hash, *hash);
1206 _ => panic!("Unexpected event"),
1210 for (preimage, _) in payments.drain(..) {
1211 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1214 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1218 fn duplicate_htlc_test() {
1219 // Test that we accept duplicate payment_hash HTLCs across the network and that
1220 // claiming/failing them are all separate and don't affect each other
1221 let chanmon_cfgs = create_chanmon_cfgs(6);
1222 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1223 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1224 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1226 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1227 create_announced_chan_between_nodes(&nodes, 0, 3);
1228 create_announced_chan_between_nodes(&nodes, 1, 3);
1229 create_announced_chan_between_nodes(&nodes, 2, 3);
1230 create_announced_chan_between_nodes(&nodes, 3, 4);
1231 create_announced_chan_between_nodes(&nodes, 3, 5);
1233 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1235 *nodes[0].network_payment_count.borrow_mut() -= 1;
1236 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1238 *nodes[0].network_payment_count.borrow_mut() -= 1;
1239 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1241 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1242 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1243 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1247 fn test_duplicate_htlc_different_direction_onchain() {
1248 // Test that ChannelMonitor doesn't generate 2 preimage txn
1249 // when we have 2 HTLCs with same preimage that go across a node
1250 // in opposite directions, even with the same payment secret.
1251 let chanmon_cfgs = create_chanmon_cfgs(2);
1252 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1253 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1254 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1256 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1259 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1261 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1263 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1264 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1265 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1267 // Provide preimage to node 0 by claiming payment
1268 nodes[0].node.claim_funds(payment_preimage);
1269 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1270 check_added_monitors!(nodes[0], 1);
1272 // Broadcast node 1 commitment txn
1273 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1275 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1276 let mut has_both_htlcs = 0; // check htlcs match ones committed
1277 for outp in remote_txn[0].output.iter() {
1278 if outp.value == 800_000 / 1000 {
1279 has_both_htlcs += 1;
1280 } else if outp.value == 900_000 / 1000 {
1281 has_both_htlcs += 1;
1284 assert_eq!(has_both_htlcs, 2);
1286 mine_transaction(&nodes[0], &remote_txn[0]);
1287 check_added_monitors!(nodes[0], 1);
1288 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1289 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1291 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1292 assert_eq!(claim_txn.len(), 3);
1294 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1295 check_spends!(claim_txn[1], remote_txn[0]);
1296 check_spends!(claim_txn[2], remote_txn[0]);
1297 let preimage_tx = &claim_txn[0];
1298 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1299 (&claim_txn[1], &claim_txn[2])
1301 (&claim_txn[2], &claim_txn[1])
1304 assert_eq!(preimage_tx.input.len(), 1);
1305 assert_eq!(preimage_bump_tx.input.len(), 1);
1307 assert_eq!(preimage_tx.input.len(), 1);
1308 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1309 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1311 assert_eq!(timeout_tx.input.len(), 1);
1312 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1313 check_spends!(timeout_tx, remote_txn[0]);
1314 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1316 let events = nodes[0].node.get_and_clear_pending_msg_events();
1317 assert_eq!(events.len(), 3);
1320 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1321 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1322 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1323 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1325 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, .. } } => {
1326 assert!(update_add_htlcs.is_empty());
1327 assert!(update_fail_htlcs.is_empty());
1328 assert_eq!(update_fulfill_htlcs.len(), 1);
1329 assert!(update_fail_malformed_htlcs.is_empty());
1330 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1332 _ => panic!("Unexpected event"),
1338 fn test_basic_channel_reserve() {
1339 let chanmon_cfgs = create_chanmon_cfgs(2);
1340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1342 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1343 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1345 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1346 let channel_reserve = chan_stat.channel_reserve_msat;
1348 // The 2* and +1 are for the fee spike reserve.
1349 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));
1350 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1351 let (mut route, our_payment_hash, _, our_payment_secret) =
1352 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1353 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1354 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1355 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1357 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1358 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1359 else { panic!("Unexpected error variant"); }
1361 _ => panic!("Unexpected error variant"),
1363 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
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 (mut route, payment_hash, _, payment_secret) =
1377 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1378 route.paths[0].hops[0].fee_msat += 1;
1379 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1380 let secp_ctx = Secp256k1::new();
1381 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1383 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1385 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1386 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1387 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1388 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1389 let msg = msgs::UpdateAddHTLC {
1392 amount_msat: htlc_msat,
1393 payment_hash: payment_hash,
1394 cltv_expiry: htlc_cltv,
1395 onion_routing_packet: onion_packet,
1396 skimmed_fee_msat: None,
1399 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1401 // Now manually create the commitment_signed message corresponding to the update_add
1402 // nodes[0] just sent. In the code for construction of this message, "local" refers
1403 // to the sender of the message, and "remote" refers to the receiver.
1405 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1407 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1409 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1410 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1411 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1412 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1413 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1414 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1415 let chan_signer = local_chan.get_signer();
1416 // Make the signer believe we validated another commitment, so we can release the secret
1417 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1419 let pubkeys = chan_signer.pubkeys();
1420 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1421 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1422 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1423 chan_signer.pubkeys().funding_pubkey)
1425 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1426 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1427 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1428 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1429 let chan_signer = remote_chan.get_signer();
1430 let pubkeys = chan_signer.pubkeys();
1431 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1432 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1433 chan_signer.pubkeys().funding_pubkey)
1436 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1437 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1438 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1440 // Build the remote commitment transaction so we can sign it, and then later use the
1441 // signature for the commitment_signed message.
1442 let local_chan_balance = 1313;
1444 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1446 amount_msat: 3460001,
1447 cltv_expiry: htlc_cltv,
1449 transaction_output_index: Some(1),
1452 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1455 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1456 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1457 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1458 let local_chan_signer = local_chan.get_signer();
1459 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1463 local_chan.context.opt_anchors(), local_funding, remote_funding,
1464 commit_tx_keys.clone(),
1466 &mut vec![(accepted_htlc_info, ())],
1467 &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1469 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1472 let commit_signed_msg = msgs::CommitmentSigned {
1475 htlc_signatures: res.1,
1477 partial_signature_with_nonce: None,
1480 // Send the commitment_signed message to the nodes[1].
1481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1482 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1484 // Send the RAA to nodes[1].
1485 let raa_msg = msgs::RevokeAndACK {
1487 per_commitment_secret: local_secret,
1488 next_per_commitment_point: next_local_point,
1490 next_local_nonce: None,
1492 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1494 let events = nodes[1].node.get_and_clear_pending_msg_events();
1495 assert_eq!(events.len(), 1);
1496 // Make sure the HTLC failed in the way we expect.
1498 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1499 assert_eq!(update_fail_htlcs.len(), 1);
1500 update_fail_htlcs[0].clone()
1502 _ => panic!("Unexpected event"),
1504 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1505 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1507 check_added_monitors!(nodes[1], 2);
1511 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1512 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1513 // Set the fee rate for the channel very high, to the point where the fundee
1514 // sending any above-dust amount would result in a channel reserve violation.
1515 // In this test we check that we would be prevented from sending an HTLC in
1517 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1520 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521 let default_config = UserConfig::default();
1522 let opt_anchors = false;
1524 let mut push_amt = 100_000_000;
1525 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1527 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1529 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1531 // Fetch a route in advance as we will be unable to once we're unable to send.
1532 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1533 // Sending exactly enough to hit the reserve amount should be accepted
1534 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1535 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1538 // However one more HTLC should be significantly over the reserve amount and fail.
1539 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1540 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1541 ), true, APIError::ChannelUnavailable { .. }, {});
1542 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1546 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1547 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1548 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1551 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1552 let default_config = UserConfig::default();
1553 let opt_anchors = false;
1555 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1556 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1557 // transaction fee with 0 HTLCs (183 sats)).
1558 let mut push_amt = 100_000_000;
1559 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1560 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1561 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1563 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1564 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1565 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1568 let (mut route, payment_hash, _, payment_secret) =
1569 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1570 route.paths[0].hops[0].fee_msat = 700_000;
1571 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1572 let secp_ctx = Secp256k1::new();
1573 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1574 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1575 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1576 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1577 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1578 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1579 let msg = msgs::UpdateAddHTLC {
1581 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1582 amount_msat: htlc_msat,
1583 payment_hash: payment_hash,
1584 cltv_expiry: htlc_cltv,
1585 onion_routing_packet: onion_packet,
1586 skimmed_fee_msat: None,
1589 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1590 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1591 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);
1592 assert_eq!(nodes[0].node.list_channels().len(), 0);
1593 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1594 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1595 check_added_monitors!(nodes[0], 1);
1596 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() });
1600 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1601 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1602 // calculating our commitment transaction fee (this was previously broken).
1603 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1604 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1608 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1609 let default_config = UserConfig::default();
1610 let opt_anchors = false;
1612 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1613 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1614 // transaction fee with 0 HTLCs (183 sats)).
1615 let mut push_amt = 100_000_000;
1616 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1617 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1618 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1620 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1621 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1622 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1623 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1624 // commitment transaction fee.
1625 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1627 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1628 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1629 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1632 // One more than the dust amt should fail, however.
1633 let (mut route, our_payment_hash, _, our_payment_secret) =
1634 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1635 route.paths[0].hops[0].fee_msat += 1;
1636 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1637 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1638 ), true, APIError::ChannelUnavailable { .. }, {});
1642 fn test_chan_init_feerate_unaffordability() {
1643 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1644 // channel reserve and feerate requirements.
1645 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1646 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1650 let default_config = UserConfig::default();
1651 let opt_anchors = false;
1653 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1655 let mut push_amt = 100_000_000;
1656 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1657 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1658 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1660 // During open, we don't have a "counterparty channel reserve" to check against, so that
1661 // requirement only comes into play on the open_channel handling side.
1662 push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1663 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1664 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1665 open_channel_msg.push_msat += 1;
1666 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1668 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1669 assert_eq!(msg_events.len(), 1);
1670 match msg_events[0] {
1671 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1672 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1674 _ => panic!("Unexpected event"),
1679 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1680 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1681 // calculating our counterparty's commitment transaction fee (this was previously broken).
1682 let chanmon_cfgs = create_chanmon_cfgs(2);
1683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1685 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1686 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1688 let payment_amt = 46000; // Dust amount
1689 // In the previous code, these first four payments would succeed.
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);
1695 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1696 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1699 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1700 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1702 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1703 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1704 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1705 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1709 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1710 let chanmon_cfgs = create_chanmon_cfgs(3);
1711 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1712 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1713 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1714 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1715 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1718 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1719 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1720 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1721 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1723 // Add a 2* and +1 for the fee spike reserve.
1724 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1725 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;
1726 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1728 // Add a pending HTLC.
1729 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1730 let payment_event_1 = {
1731 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1732 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1733 check_added_monitors!(nodes[0], 1);
1735 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1736 assert_eq!(events.len(), 1);
1737 SendEvent::from_event(events.remove(0))
1739 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1741 // Attempt to trigger a channel reserve violation --> payment failure.
1742 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1743 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;
1744 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1745 let mut route_2 = route_1.clone();
1746 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1748 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1749 let secp_ctx = Secp256k1::new();
1750 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1751 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1752 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1753 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1754 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1755 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1756 let msg = msgs::UpdateAddHTLC {
1759 amount_msat: htlc_msat + 1,
1760 payment_hash: our_payment_hash_1,
1761 cltv_expiry: htlc_cltv,
1762 onion_routing_packet: onion_packet,
1763 skimmed_fee_msat: None,
1766 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1767 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1768 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1769 assert_eq!(nodes[1].node.list_channels().len(), 1);
1770 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1771 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1772 check_added_monitors!(nodes[1], 1);
1773 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1777 fn test_inbound_outbound_capacity_is_not_zero() {
1778 let chanmon_cfgs = create_chanmon_cfgs(2);
1779 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1780 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1781 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1782 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1783 let channels0 = node_chanmgrs[0].list_channels();
1784 let channels1 = node_chanmgrs[1].list_channels();
1785 let default_config = UserConfig::default();
1786 assert_eq!(channels0.len(), 1);
1787 assert_eq!(channels1.len(), 1);
1789 let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1790 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1791 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1793 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1794 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1797 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1798 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1802 fn test_channel_reserve_holding_cell_htlcs() {
1803 let chanmon_cfgs = create_chanmon_cfgs(3);
1804 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1805 // When this test was written, the default base fee floated based on the HTLC count.
1806 // It is now fixed, so we simply set the fee to the expected value here.
1807 let mut config = test_default_channel_config();
1808 config.channel_config.forwarding_fee_base_msat = 239;
1809 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1810 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1811 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1812 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1814 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1815 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1817 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1818 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1820 macro_rules! expect_forward {
1822 let mut events = $node.node.get_and_clear_pending_msg_events();
1823 assert_eq!(events.len(), 1);
1824 check_added_monitors!($node, 1);
1825 let payment_event = SendEvent::from_event(events.remove(0));
1830 let feemsat = 239; // set above
1831 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1832 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1833 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1835 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1837 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1839 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1840 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1841 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1842 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1843 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1845 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1846 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1847 ), true, APIError::ChannelUnavailable { .. }, {});
1848 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1851 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1852 // nodes[0]'s wealth
1854 let amt_msat = recv_value_0 + total_fee_msat;
1855 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1856 // Also, ensure that each payment has enough to be over the dust limit to
1857 // ensure it'll be included in each commit tx fee calculation.
1858 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1859 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1860 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1864 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1865 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1866 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1867 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1868 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1870 let (stat01_, stat11_, stat12_, stat22_) = (
1871 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1872 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1873 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1874 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1877 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1878 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1879 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1880 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1881 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1884 // adding pending output.
1885 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1886 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1887 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1888 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1889 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1890 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1891 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1892 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1893 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1895 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1896 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1897 let amt_msat_1 = recv_value_1 + total_fee_msat;
1899 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);
1900 let payment_event_1 = {
1901 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1902 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1903 check_added_monitors!(nodes[0], 1);
1905 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1906 assert_eq!(events.len(), 1);
1907 SendEvent::from_event(events.remove(0))
1909 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1911 // channel reserve test with htlc pending output > 0
1912 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1914 let mut route = route_1.clone();
1915 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1916 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1917 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1918 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1919 ), true, APIError::ChannelUnavailable { .. }, {});
1920 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1923 // split the rest to test holding cell
1924 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1925 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1926 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1927 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1929 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1930 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);
1933 // now see if they go through on both sides
1934 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);
1935 // but this will stuck in the holding cell
1936 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1937 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1938 check_added_monitors!(nodes[0], 0);
1939 let events = nodes[0].node.get_and_clear_pending_events();
1940 assert_eq!(events.len(), 0);
1942 // test with outbound holding cell amount > 0
1944 let (mut route, our_payment_hash, _, our_payment_secret) =
1945 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1946 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1947 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1948 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1949 ), true, APIError::ChannelUnavailable { .. }, {});
1950 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953 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);
1954 // this will also stuck in the holding cell
1955 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1956 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1957 check_added_monitors!(nodes[0], 0);
1958 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1959 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1961 // flush the pending htlc
1962 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1963 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1964 check_added_monitors!(nodes[1], 1);
1966 // the pending htlc should be promoted to committed
1967 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1968 check_added_monitors!(nodes[0], 1);
1969 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1971 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1972 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1973 // No commitment_signed so get_event_msg's assert(len == 1) passes
1974 check_added_monitors!(nodes[0], 1);
1976 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1977 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1978 check_added_monitors!(nodes[1], 1);
1980 expect_pending_htlcs_forwardable!(nodes[1]);
1982 let ref payment_event_11 = expect_forward!(nodes[1]);
1983 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1984 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1986 expect_pending_htlcs_forwardable!(nodes[2]);
1987 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1989 // flush the htlcs in the holding cell
1990 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1991 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1992 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1993 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1994 expect_pending_htlcs_forwardable!(nodes[1]);
1996 let ref payment_event_3 = expect_forward!(nodes[1]);
1997 assert_eq!(payment_event_3.msgs.len(), 2);
1998 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1999 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2001 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2002 expect_pending_htlcs_forwardable!(nodes[2]);
2004 let events = nodes[2].node.get_and_clear_pending_events();
2005 assert_eq!(events.len(), 2);
2007 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2008 assert_eq!(our_payment_hash_21, *payment_hash);
2009 assert_eq!(recv_value_21, amount_msat);
2010 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2011 assert_eq!(via_channel_id, Some(chan_2.2));
2013 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2014 assert!(payment_preimage.is_none());
2015 assert_eq!(our_payment_secret_21, *payment_secret);
2017 _ => panic!("expected PaymentPurpose::InvoicePayment")
2020 _ => panic!("Unexpected event"),
2023 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2024 assert_eq!(our_payment_hash_22, *payment_hash);
2025 assert_eq!(recv_value_22, amount_msat);
2026 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2027 assert_eq!(via_channel_id, Some(chan_2.2));
2029 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2030 assert!(payment_preimage.is_none());
2031 assert_eq!(our_payment_secret_22, *payment_secret);
2033 _ => panic!("expected PaymentPurpose::InvoicePayment")
2036 _ => panic!("Unexpected event"),
2039 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2040 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2041 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2043 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2044 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2045 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2047 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2048 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);
2049 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2050 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2051 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2053 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2054 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2058 fn channel_reserve_in_flight_removes() {
2059 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2060 // can send to its counterparty, but due to update ordering, the other side may not yet have
2061 // considered those HTLCs fully removed.
2062 // This tests that we don't count HTLCs which will not be included in the next remote
2063 // commitment transaction towards the reserve value (as it implies no commitment transaction
2064 // will be generated which violates the remote reserve value).
2065 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2067 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2068 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2069 // you only consider the value of the first HTLC, it may not),
2070 // * start routing a third HTLC from A to B,
2071 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2072 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2073 // * deliver the first fulfill from B
2074 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2076 // * deliver A's response CS and RAA.
2077 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2078 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2079 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2080 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2081 let chanmon_cfgs = create_chanmon_cfgs(2);
2082 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2083 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2084 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2085 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2087 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2088 // Route the first two HTLCs.
2089 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2090 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2091 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2093 // Start routing the third HTLC (this is just used to get everyone in the right state).
2094 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2096 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2097 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2098 check_added_monitors!(nodes[0], 1);
2099 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2100 assert_eq!(events.len(), 1);
2101 SendEvent::from_event(events.remove(0))
2104 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2105 // initial fulfill/CS.
2106 nodes[1].node.claim_funds(payment_preimage_1);
2107 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2108 check_added_monitors!(nodes[1], 1);
2109 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2111 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2112 // remove the second HTLC when we send the HTLC back from B to A.
2113 nodes[1].node.claim_funds(payment_preimage_2);
2114 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2115 check_added_monitors!(nodes[1], 1);
2116 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2118 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2119 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2120 check_added_monitors!(nodes[0], 1);
2121 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2122 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2124 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2125 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2126 check_added_monitors!(nodes[1], 1);
2127 // B is already AwaitingRAA, so cant generate a CS here
2128 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2130 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2131 check_added_monitors!(nodes[1], 1);
2132 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2134 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2135 check_added_monitors!(nodes[0], 1);
2136 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2138 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2139 check_added_monitors!(nodes[1], 1);
2140 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2142 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2143 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2144 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2145 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2146 // on-chain as necessary).
2147 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2148 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2149 check_added_monitors!(nodes[0], 1);
2150 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2151 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2153 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2154 check_added_monitors!(nodes[1], 1);
2155 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2157 expect_pending_htlcs_forwardable!(nodes[1]);
2158 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2160 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2161 // resolve the second HTLC from A's point of view.
2162 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2163 check_added_monitors!(nodes[0], 1);
2164 expect_payment_path_successful!(nodes[0]);
2165 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2167 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2168 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2169 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2171 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2172 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2173 check_added_monitors!(nodes[1], 1);
2174 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2175 assert_eq!(events.len(), 1);
2176 SendEvent::from_event(events.remove(0))
2179 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2180 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2181 check_added_monitors!(nodes[0], 1);
2182 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2184 // Now just resolve all the outstanding messages/HTLCs for completeness...
2186 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2187 check_added_monitors!(nodes[1], 1);
2188 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2190 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2191 check_added_monitors!(nodes[1], 1);
2193 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2194 check_added_monitors!(nodes[0], 1);
2195 expect_payment_path_successful!(nodes[0]);
2196 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2198 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2199 check_added_monitors!(nodes[1], 1);
2200 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2203 check_added_monitors!(nodes[0], 1);
2205 expect_pending_htlcs_forwardable!(nodes[0]);
2206 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2208 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2209 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2213 fn channel_monitor_network_test() {
2214 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2215 // tests that ChannelMonitor is able to recover from various states.
2216 let chanmon_cfgs = create_chanmon_cfgs(5);
2217 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2218 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2219 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2221 // Create some initial channels
2222 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2223 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2224 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2225 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2227 // Make sure all nodes are at the same starting height
2228 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2229 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2230 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2231 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2232 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2234 // Rebalance the network a bit by relaying one payment through all the channels...
2235 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2236 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2237 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2238 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2240 // Simple case with no pending HTLCs:
2241 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2242 check_added_monitors!(nodes[1], 1);
2243 check_closed_broadcast!(nodes[1], true);
2245 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2246 assert_eq!(node_txn.len(), 1);
2247 mine_transaction(&nodes[0], &node_txn[0]);
2248 check_added_monitors!(nodes[0], 1);
2249 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2251 check_closed_broadcast!(nodes[0], true);
2252 assert_eq!(nodes[0].node.list_channels().len(), 0);
2253 assert_eq!(nodes[1].node.list_channels().len(), 1);
2254 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2255 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2257 // One pending HTLC is discarded by the force-close:
2258 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2260 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2261 // broadcasted until we reach the timelock time).
2262 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2263 check_closed_broadcast!(nodes[1], true);
2264 check_added_monitors!(nodes[1], 1);
2266 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2267 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2268 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2269 mine_transaction(&nodes[2], &node_txn[0]);
2270 check_added_monitors!(nodes[2], 1);
2271 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2273 check_closed_broadcast!(nodes[2], true);
2274 assert_eq!(nodes[1].node.list_channels().len(), 0);
2275 assert_eq!(nodes[2].node.list_channels().len(), 1);
2276 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2277 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2279 macro_rules! claim_funds {
2280 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2282 $node.node.claim_funds($preimage);
2283 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2284 check_added_monitors!($node, 1);
2286 let events = $node.node.get_and_clear_pending_msg_events();
2287 assert_eq!(events.len(), 1);
2289 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2290 assert!(update_add_htlcs.is_empty());
2291 assert!(update_fail_htlcs.is_empty());
2292 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2294 _ => panic!("Unexpected event"),
2300 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2301 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2302 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2303 check_added_monitors!(nodes[2], 1);
2304 check_closed_broadcast!(nodes[2], true);
2305 let node2_commitment_txid;
2307 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2308 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2309 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2310 node2_commitment_txid = node_txn[0].txid();
2312 // Claim the payment on nodes[3], giving it knowledge of the preimage
2313 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2314 mine_transaction(&nodes[3], &node_txn[0]);
2315 check_added_monitors!(nodes[3], 1);
2316 check_preimage_claim(&nodes[3], &node_txn);
2318 check_closed_broadcast!(nodes[3], true);
2319 assert_eq!(nodes[2].node.list_channels().len(), 0);
2320 assert_eq!(nodes[3].node.list_channels().len(), 1);
2321 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2322 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2324 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2325 // confusing us in the following tests.
2326 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2328 // One pending HTLC to time out:
2329 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2330 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2333 let (close_chan_update_1, close_chan_update_2) = {
2334 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2335 let events = nodes[3].node.get_and_clear_pending_msg_events();
2336 assert_eq!(events.len(), 2);
2337 let close_chan_update_1 = match events[0] {
2338 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2341 _ => panic!("Unexpected event"),
2344 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2345 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2347 _ => panic!("Unexpected event"),
2349 check_added_monitors!(nodes[3], 1);
2351 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2353 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2354 node_txn.retain(|tx| {
2355 if tx.input[0].previous_output.txid == node2_commitment_txid {
2361 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2363 // Claim the payment on nodes[4], giving it knowledge of the preimage
2364 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2366 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2367 let events = nodes[4].node.get_and_clear_pending_msg_events();
2368 assert_eq!(events.len(), 2);
2369 let close_chan_update_2 = match events[0] {
2370 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2373 _ => panic!("Unexpected event"),
2376 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2377 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2379 _ => panic!("Unexpected event"),
2381 check_added_monitors!(nodes[4], 1);
2382 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2384 mine_transaction(&nodes[4], &node_txn[0]);
2385 check_preimage_claim(&nodes[4], &node_txn);
2386 (close_chan_update_1, close_chan_update_2)
2388 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2389 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2390 assert_eq!(nodes[3].node.list_channels().len(), 0);
2391 assert_eq!(nodes[4].node.list_channels().len(), 0);
2393 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2394 ChannelMonitorUpdateStatus::Completed);
2395 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2396 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2400 fn test_justice_tx_htlc_timeout() {
2401 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2402 let mut alice_config = UserConfig::default();
2403 alice_config.channel_handshake_config.announced_channel = true;
2404 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2405 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2406 let mut bob_config = UserConfig::default();
2407 bob_config.channel_handshake_config.announced_channel = true;
2408 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2409 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2410 let user_cfgs = [Some(alice_config), Some(bob_config)];
2411 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2412 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2413 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2416 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2417 // Create some new channels:
2418 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2420 // A pending HTLC which will be revoked:
2421 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2422 // Get the will-be-revoked local txn from nodes[0]
2423 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2424 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2425 assert_eq!(revoked_local_txn[0].input.len(), 1);
2426 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2427 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2428 assert_eq!(revoked_local_txn[1].input.len(), 1);
2429 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2430 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2431 // Revoke the old state
2432 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2435 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2437 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2438 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2439 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2440 check_spends!(node_txn[0], revoked_local_txn[0]);
2441 node_txn.swap_remove(0);
2443 check_added_monitors!(nodes[1], 1);
2444 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2445 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2447 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2448 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2449 // Verify broadcast of revoked HTLC-timeout
2450 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2451 check_added_monitors!(nodes[0], 1);
2452 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2453 // Broadcast revoked HTLC-timeout on node 1
2454 mine_transaction(&nodes[1], &node_txn[1]);
2455 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2457 get_announce_close_broadcast_events(&nodes, 0, 1);
2458 assert_eq!(nodes[0].node.list_channels().len(), 0);
2459 assert_eq!(nodes[1].node.list_channels().len(), 0);
2463 fn test_justice_tx_htlc_success() {
2464 // Test justice txn built on revoked HTLC-Success tx, against both sides
2465 let mut alice_config = UserConfig::default();
2466 alice_config.channel_handshake_config.announced_channel = true;
2467 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2468 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2469 let mut bob_config = UserConfig::default();
2470 bob_config.channel_handshake_config.announced_channel = true;
2471 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2472 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2473 let user_cfgs = [Some(alice_config), Some(bob_config)];
2474 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2475 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2476 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2480 // Create some new channels:
2481 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2483 // A pending HTLC which will be revoked:
2484 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2485 // Get the will-be-revoked local txn from B
2486 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2487 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2488 assert_eq!(revoked_local_txn[0].input.len(), 1);
2489 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2490 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2491 // Revoke the old state
2492 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2494 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2496 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2497 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2498 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2500 check_spends!(node_txn[0], revoked_local_txn[0]);
2501 node_txn.swap_remove(0);
2503 check_added_monitors!(nodes[0], 1);
2504 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2506 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2507 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2508 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2509 check_added_monitors!(nodes[1], 1);
2510 mine_transaction(&nodes[0], &node_txn[1]);
2511 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2512 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2514 get_announce_close_broadcast_events(&nodes, 0, 1);
2515 assert_eq!(nodes[0].node.list_channels().len(), 0);
2516 assert_eq!(nodes[1].node.list_channels().len(), 0);
2520 fn revoked_output_claim() {
2521 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2522 // transaction is broadcast by its counterparty
2523 let chanmon_cfgs = create_chanmon_cfgs(2);
2524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2527 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2528 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2529 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2530 assert_eq!(revoked_local_txn.len(), 1);
2531 // Only output is the full channel value back to nodes[0]:
2532 assert_eq!(revoked_local_txn[0].output.len(), 1);
2533 // Send a payment through, updating everyone's latest commitment txn
2534 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2536 // Inform nodes[1] that nodes[0] broadcast a stale tx
2537 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2538 check_added_monitors!(nodes[1], 1);
2539 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2540 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2541 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2543 check_spends!(node_txn[0], revoked_local_txn[0]);
2545 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2546 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2547 get_announce_close_broadcast_events(&nodes, 0, 1);
2548 check_added_monitors!(nodes[0], 1);
2549 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2553 fn claim_htlc_outputs_shared_tx() {
2554 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2555 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2556 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2557 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2558 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2559 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2561 // Create some new channel:
2562 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2564 // Rebalance the network to generate htlc in the two directions
2565 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2566 // 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
2567 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2568 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2570 // Get the will-be-revoked local txn from node[0]
2571 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2572 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2573 assert_eq!(revoked_local_txn[0].input.len(), 1);
2574 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2575 assert_eq!(revoked_local_txn[1].input.len(), 1);
2576 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2577 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2578 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2580 //Revoke the old state
2581 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2584 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2585 check_added_monitors!(nodes[0], 1);
2586 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2587 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2588 check_added_monitors!(nodes[1], 1);
2589 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2590 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2591 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2593 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2594 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2596 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2597 check_spends!(node_txn[0], revoked_local_txn[0]);
2599 let mut witness_lens = BTreeSet::new();
2600 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2601 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2602 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2603 assert_eq!(witness_lens.len(), 3);
2604 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2605 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2606 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2608 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2609 // ANTI_REORG_DELAY confirmations.
2610 mine_transaction(&nodes[1], &node_txn[0]);
2611 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2612 expect_payment_failed!(nodes[1], payment_hash_2, false);
2614 get_announce_close_broadcast_events(&nodes, 0, 1);
2615 assert_eq!(nodes[0].node.list_channels().len(), 0);
2616 assert_eq!(nodes[1].node.list_channels().len(), 0);
2620 fn claim_htlc_outputs_single_tx() {
2621 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2622 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2623 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2626 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2628 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2630 // Rebalance the network to generate htlc in the two directions
2631 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2632 // 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
2633 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2634 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2635 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2637 // Get the will-be-revoked local txn from node[0]
2638 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2640 //Revoke the old state
2641 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2644 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2645 check_added_monitors!(nodes[0], 1);
2646 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2647 check_added_monitors!(nodes[1], 1);
2648 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2649 let mut events = nodes[0].node.get_and_clear_pending_events();
2650 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2651 match events.last().unwrap() {
2652 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2653 _ => panic!("Unexpected event"),
2656 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2657 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2659 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2661 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2662 assert_eq!(node_txn[0].input.len(), 1);
2663 check_spends!(node_txn[0], chan_1.3);
2664 assert_eq!(node_txn[1].input.len(), 1);
2665 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2666 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2667 check_spends!(node_txn[1], node_txn[0]);
2669 // Filter out any non justice transactions.
2670 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2671 assert!(node_txn.len() > 3);
2673 assert_eq!(node_txn[0].input.len(), 1);
2674 assert_eq!(node_txn[1].input.len(), 1);
2675 assert_eq!(node_txn[2].input.len(), 1);
2677 check_spends!(node_txn[0], revoked_local_txn[0]);
2678 check_spends!(node_txn[1], revoked_local_txn[0]);
2679 check_spends!(node_txn[2], revoked_local_txn[0]);
2681 let mut witness_lens = BTreeSet::new();
2682 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2683 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2684 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2685 assert_eq!(witness_lens.len(), 3);
2686 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2687 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2688 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2690 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2691 // ANTI_REORG_DELAY confirmations.
2692 mine_transaction(&nodes[1], &node_txn[0]);
2693 mine_transaction(&nodes[1], &node_txn[1]);
2694 mine_transaction(&nodes[1], &node_txn[2]);
2695 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2696 expect_payment_failed!(nodes[1], payment_hash_2, false);
2698 get_announce_close_broadcast_events(&nodes, 0, 1);
2699 assert_eq!(nodes[0].node.list_channels().len(), 0);
2700 assert_eq!(nodes[1].node.list_channels().len(), 0);
2704 fn test_htlc_on_chain_success() {
2705 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2706 // the preimage backward accordingly. So here we test that ChannelManager is
2707 // broadcasting the right event to other nodes in payment path.
2708 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2709 // A --------------------> B ----------------------> C (preimage)
2710 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2711 // commitment transaction was broadcast.
2712 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2714 // B should be able to claim via preimage if A then broadcasts its local tx.
2715 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2716 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2717 // PaymentSent event).
2719 let chanmon_cfgs = create_chanmon_cfgs(3);
2720 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2721 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2722 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2724 // Create some initial channels
2725 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2726 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2728 // Ensure all nodes are at the same height
2729 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2730 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2731 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2732 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2734 // Rebalance the network a bit by relaying one payment through all the channels...
2735 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2736 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2738 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2739 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2741 // Broadcast legit commitment tx from C on B's chain
2742 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2743 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2744 assert_eq!(commitment_tx.len(), 1);
2745 check_spends!(commitment_tx[0], chan_2.3);
2746 nodes[2].node.claim_funds(our_payment_preimage);
2747 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2748 nodes[2].node.claim_funds(our_payment_preimage_2);
2749 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2750 check_added_monitors!(nodes[2], 2);
2751 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2752 assert!(updates.update_add_htlcs.is_empty());
2753 assert!(updates.update_fail_htlcs.is_empty());
2754 assert!(updates.update_fail_malformed_htlcs.is_empty());
2755 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2757 mine_transaction(&nodes[2], &commitment_tx[0]);
2758 check_closed_broadcast!(nodes[2], true);
2759 check_added_monitors!(nodes[2], 1);
2760 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2761 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2762 assert_eq!(node_txn.len(), 2);
2763 check_spends!(node_txn[0], commitment_tx[0]);
2764 check_spends!(node_txn[1], commitment_tx[0]);
2765 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2766 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2767 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2768 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2769 assert_eq!(node_txn[0].lock_time.0, 0);
2770 assert_eq!(node_txn[1].lock_time.0, 0);
2772 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2773 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2774 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2776 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2777 assert_eq!(added_monitors.len(), 1);
2778 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2779 added_monitors.clear();
2781 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2782 assert_eq!(forwarded_events.len(), 3);
2783 match forwarded_events[0] {
2784 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2785 _ => panic!("Unexpected event"),
2787 let chan_id = Some(chan_1.2);
2788 match forwarded_events[1] {
2789 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2790 assert_eq!(fee_earned_msat, Some(1000));
2791 assert_eq!(prev_channel_id, chan_id);
2792 assert_eq!(claim_from_onchain_tx, true);
2793 assert_eq!(next_channel_id, Some(chan_2.2));
2794 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2798 match forwarded_events[2] {
2799 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2800 assert_eq!(fee_earned_msat, Some(1000));
2801 assert_eq!(prev_channel_id, chan_id);
2802 assert_eq!(claim_from_onchain_tx, true);
2803 assert_eq!(next_channel_id, Some(chan_2.2));
2804 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2808 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2810 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2811 assert_eq!(added_monitors.len(), 2);
2812 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2813 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2814 added_monitors.clear();
2816 assert_eq!(events.len(), 3);
2818 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2819 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2821 match nodes_2_event {
2822 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2823 _ => panic!("Unexpected event"),
2826 match nodes_0_event {
2827 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, .. } } => {
2828 assert!(update_add_htlcs.is_empty());
2829 assert!(update_fail_htlcs.is_empty());
2830 assert_eq!(update_fulfill_htlcs.len(), 1);
2831 assert!(update_fail_malformed_htlcs.is_empty());
2832 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2834 _ => panic!("Unexpected event"),
2837 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2839 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2840 _ => panic!("Unexpected event"),
2843 macro_rules! check_tx_local_broadcast {
2844 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2845 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2846 assert_eq!(node_txn.len(), 2);
2847 // Node[1]: 2 * HTLC-timeout tx
2848 // Node[0]: 2 * HTLC-timeout tx
2849 check_spends!(node_txn[0], $commitment_tx);
2850 check_spends!(node_txn[1], $commitment_tx);
2851 assert_ne!(node_txn[0].lock_time.0, 0);
2852 assert_ne!(node_txn[1].lock_time.0, 0);
2854 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2855 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2856 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2857 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2859 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2860 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2861 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2862 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2867 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2868 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2870 // Broadcast legit commitment tx from A on B's chain
2871 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2872 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2873 check_spends!(node_a_commitment_tx[0], chan_1.3);
2874 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2875 check_closed_broadcast!(nodes[1], true);
2876 check_added_monitors!(nodes[1], 1);
2877 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2878 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2879 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2880 let commitment_spend =
2881 if node_txn.len() == 1 {
2884 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2885 // FullBlockViaListen
2886 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2887 check_spends!(node_txn[1], commitment_tx[0]);
2888 check_spends!(node_txn[2], commitment_tx[0]);
2889 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2892 check_spends!(node_txn[0], commitment_tx[0]);
2893 check_spends!(node_txn[1], commitment_tx[0]);
2894 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2899 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2900 assert_eq!(commitment_spend.input.len(), 2);
2901 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2902 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2903 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2904 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2905 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2906 // we already checked the same situation with A.
2908 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2909 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2910 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2911 check_closed_broadcast!(nodes[0], true);
2912 check_added_monitors!(nodes[0], 1);
2913 let events = nodes[0].node.get_and_clear_pending_events();
2914 assert_eq!(events.len(), 5);
2915 let mut first_claimed = false;
2916 for event in events {
2918 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2919 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2920 assert!(!first_claimed);
2921 first_claimed = true;
2923 assert_eq!(payment_preimage, our_payment_preimage_2);
2924 assert_eq!(payment_hash, payment_hash_2);
2927 Event::PaymentPathSuccessful { .. } => {},
2928 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2929 _ => panic!("Unexpected event"),
2932 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2935 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2936 // Test that in case of a unilateral close onchain, we detect the state of output and
2937 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2938 // broadcasting the right event to other nodes in payment path.
2939 // A ------------------> B ----------------------> C (timeout)
2940 // B's commitment tx C's commitment tx
2942 // B's HTLC timeout tx B's timeout tx
2944 let chanmon_cfgs = create_chanmon_cfgs(3);
2945 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2946 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2947 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2948 *nodes[0].connect_style.borrow_mut() = connect_style;
2949 *nodes[1].connect_style.borrow_mut() = connect_style;
2950 *nodes[2].connect_style.borrow_mut() = connect_style;
2952 // Create some intial channels
2953 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2954 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2956 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2957 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2958 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2960 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2962 // Broadcast legit commitment tx from C on B's chain
2963 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2964 check_spends!(commitment_tx[0], chan_2.3);
2965 nodes[2].node.fail_htlc_backwards(&payment_hash);
2966 check_added_monitors!(nodes[2], 0);
2967 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2968 check_added_monitors!(nodes[2], 1);
2970 let events = nodes[2].node.get_and_clear_pending_msg_events();
2971 assert_eq!(events.len(), 1);
2973 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, .. } } => {
2974 assert!(update_add_htlcs.is_empty());
2975 assert!(!update_fail_htlcs.is_empty());
2976 assert!(update_fulfill_htlcs.is_empty());
2977 assert!(update_fail_malformed_htlcs.is_empty());
2978 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2980 _ => panic!("Unexpected event"),
2982 mine_transaction(&nodes[2], &commitment_tx[0]);
2983 check_closed_broadcast!(nodes[2], true);
2984 check_added_monitors!(nodes[2], 1);
2985 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2986 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2987 assert_eq!(node_txn.len(), 0);
2989 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2990 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2991 mine_transaction(&nodes[1], &commitment_tx[0]);
2992 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2993 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2995 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2996 if nodes[1].connect_style.borrow().skips_blocks() {
2997 assert_eq!(txn.len(), 1);
2999 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3001 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3002 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3006 mine_transaction(&nodes[1], &timeout_tx);
3007 check_added_monitors!(nodes[1], 1);
3008 check_closed_broadcast!(nodes[1], true);
3010 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3012 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 }]);
3013 check_added_monitors!(nodes[1], 1);
3014 let events = nodes[1].node.get_and_clear_pending_msg_events();
3015 assert_eq!(events.len(), 1);
3017 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, .. } } => {
3018 assert!(update_add_htlcs.is_empty());
3019 assert!(!update_fail_htlcs.is_empty());
3020 assert!(update_fulfill_htlcs.is_empty());
3021 assert!(update_fail_malformed_htlcs.is_empty());
3022 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3024 _ => panic!("Unexpected event"),
3027 // Broadcast legit commitment tx from B on A's chain
3028 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3029 check_spends!(commitment_tx[0], chan_1.3);
3031 mine_transaction(&nodes[0], &commitment_tx[0]);
3032 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3034 check_closed_broadcast!(nodes[0], true);
3035 check_added_monitors!(nodes[0], 1);
3036 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3037 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3038 assert_eq!(node_txn.len(), 1);
3039 check_spends!(node_txn[0], commitment_tx[0]);
3040 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3044 fn test_htlc_on_chain_timeout() {
3045 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3046 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3047 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3051 fn test_simple_commitment_revoked_fail_backward() {
3052 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3053 // and fail backward accordingly.
3055 let chanmon_cfgs = create_chanmon_cfgs(3);
3056 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3057 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3058 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3060 // Create some initial channels
3061 create_announced_chan_between_nodes(&nodes, 0, 1);
3062 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3064 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3065 // Get the will-be-revoked local txn from nodes[2]
3066 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3067 // Revoke the old state
3068 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3070 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3072 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3073 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3074 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3075 check_added_monitors!(nodes[1], 1);
3076 check_closed_broadcast!(nodes[1], true);
3078 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 }]);
3079 check_added_monitors!(nodes[1], 1);
3080 let events = nodes[1].node.get_and_clear_pending_msg_events();
3081 assert_eq!(events.len(), 1);
3083 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, .. } } => {
3084 assert!(update_add_htlcs.is_empty());
3085 assert_eq!(update_fail_htlcs.len(), 1);
3086 assert!(update_fulfill_htlcs.is_empty());
3087 assert!(update_fail_malformed_htlcs.is_empty());
3088 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3090 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3091 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3092 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3094 _ => panic!("Unexpected event"),
3098 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3099 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3100 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3101 // commitment transaction anymore.
3102 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3103 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3104 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3105 // technically disallowed and we should probably handle it reasonably.
3106 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3107 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3109 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3110 // commitment_signed (implying it will be in the latest remote commitment transaction).
3111 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3112 // and once they revoke the previous commitment transaction (allowing us to send a new
3113 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3114 let chanmon_cfgs = create_chanmon_cfgs(3);
3115 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3116 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3117 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3119 // Create some initial channels
3120 create_announced_chan_between_nodes(&nodes, 0, 1);
3121 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3123 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 });
3124 // Get the will-be-revoked local txn from nodes[2]
3125 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3126 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3127 // Revoke the old state
3128 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3130 let value = if use_dust {
3131 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3132 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3133 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3134 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context.holder_dust_limit_satoshis * 1000
3137 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3138 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3139 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3141 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3142 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_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 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3152 // Drop the last RAA from 3 -> 2
3154 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3155 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3156 check_added_monitors!(nodes[2], 1);
3157 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3158 assert!(updates.update_add_htlcs.is_empty());
3159 assert!(updates.update_fulfill_htlcs.is_empty());
3160 assert!(updates.update_fail_malformed_htlcs.is_empty());
3161 assert_eq!(updates.update_fail_htlcs.len(), 1);
3162 assert!(updates.update_fee.is_none());
3163 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3164 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3165 check_added_monitors!(nodes[1], 1);
3166 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3167 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3168 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3169 check_added_monitors!(nodes[2], 1);
3171 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3172 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3173 check_added_monitors!(nodes[2], 1);
3174 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3175 assert!(updates.update_add_htlcs.is_empty());
3176 assert!(updates.update_fulfill_htlcs.is_empty());
3177 assert!(updates.update_fail_malformed_htlcs.is_empty());
3178 assert_eq!(updates.update_fail_htlcs.len(), 1);
3179 assert!(updates.update_fee.is_none());
3180 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3181 // At this point first_payment_hash has dropped out of the latest two commitment
3182 // transactions that nodes[1] is tracking...
3183 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3184 check_added_monitors!(nodes[1], 1);
3185 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3186 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3187 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3188 check_added_monitors!(nodes[2], 1);
3190 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3191 // on nodes[2]'s RAA.
3192 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3193 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3194 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3195 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3196 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3197 check_added_monitors!(nodes[1], 0);
3200 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3201 // One monitor for the new revocation preimage, no second on as we won't generate a new
3202 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3203 check_added_monitors!(nodes[1], 1);
3204 let events = nodes[1].node.get_and_clear_pending_events();
3205 assert_eq!(events.len(), 2);
3207 Event::PendingHTLCsForwardable { .. } => { },
3208 _ => panic!("Unexpected event"),
3211 Event::HTLCHandlingFailed { .. } => { },
3212 _ => panic!("Unexpected event"),
3214 // Deliberately don't process the pending fail-back so they all fail back at once after
3215 // block connection just like the !deliver_bs_raa case
3218 let mut failed_htlcs = HashSet::new();
3219 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3221 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3222 check_added_monitors!(nodes[1], 1);
3223 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3225 let events = nodes[1].node.get_and_clear_pending_events();
3226 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3228 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3229 _ => panic!("Unexepected event"),
3232 Event::PaymentPathFailed { ref payment_hash, .. } => {
3233 assert_eq!(*payment_hash, fourth_payment_hash);
3235 _ => panic!("Unexpected event"),
3238 Event::PaymentFailed { ref payment_hash, .. } => {
3239 assert_eq!(*payment_hash, fourth_payment_hash);
3241 _ => panic!("Unexpected event"),
3244 nodes[1].node.process_pending_htlc_forwards();
3245 check_added_monitors!(nodes[1], 1);
3247 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3248 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
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::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3254 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3255 assert_eq!(update_add_htlcs.len(), 1);
3256 assert!(update_fulfill_htlcs.is_empty());
3257 assert!(update_fail_htlcs.is_empty());
3258 assert!(update_fail_malformed_htlcs.is_empty());
3260 _ => panic!("Unexpected event"),
3264 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3265 match nodes_2_event {
3266 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3267 assert_eq!(channel_id, chan_2.2);
3268 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3270 _ => panic!("Unexpected event"),
3273 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3274 match nodes_0_event {
3275 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, .. } } => {
3276 assert!(update_add_htlcs.is_empty());
3277 assert_eq!(update_fail_htlcs.len(), 3);
3278 assert!(update_fulfill_htlcs.is_empty());
3279 assert!(update_fail_malformed_htlcs.is_empty());
3280 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3282 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3283 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3284 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3286 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3288 let events = nodes[0].node.get_and_clear_pending_events();
3289 assert_eq!(events.len(), 6);
3291 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3292 assert!(failed_htlcs.insert(payment_hash.0));
3293 // If we delivered B's RAA we got an unknown preimage error, not something
3294 // that we should update our routing table for.
3295 if !deliver_bs_raa {
3296 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3299 _ => panic!("Unexpected event"),
3302 Event::PaymentFailed { ref payment_hash, .. } => {
3303 assert_eq!(*payment_hash, first_payment_hash);
3305 _ => panic!("Unexpected event"),
3308 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3309 assert!(failed_htlcs.insert(payment_hash.0));
3311 _ => panic!("Unexpected event"),
3314 Event::PaymentFailed { ref payment_hash, .. } => {
3315 assert_eq!(*payment_hash, second_payment_hash);
3317 _ => panic!("Unexpected event"),
3320 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3321 assert!(failed_htlcs.insert(payment_hash.0));
3323 _ => panic!("Unexpected event"),
3326 Event::PaymentFailed { ref payment_hash, .. } => {
3327 assert_eq!(*payment_hash, third_payment_hash);
3329 _ => panic!("Unexpected event"),
3332 _ => panic!("Unexpected event"),
3335 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3337 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3338 _ => panic!("Unexpected event"),
3341 assert!(failed_htlcs.contains(&first_payment_hash.0));
3342 assert!(failed_htlcs.contains(&second_payment_hash.0));
3343 assert!(failed_htlcs.contains(&third_payment_hash.0));
3347 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3348 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3349 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3350 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3351 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3355 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3356 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3357 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3358 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3359 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3363 fn fail_backward_pending_htlc_upon_channel_failure() {
3364 let chanmon_cfgs = create_chanmon_cfgs(2);
3365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3367 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3368 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3370 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3372 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3373 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3374 PaymentId(payment_hash.0)).unwrap();
3375 check_added_monitors!(nodes[0], 1);
3377 let payment_event = {
3378 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3379 assert_eq!(events.len(), 1);
3380 SendEvent::from_event(events.remove(0))
3382 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3383 assert_eq!(payment_event.msgs.len(), 1);
3386 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3387 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3389 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3390 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3391 check_added_monitors!(nodes[0], 0);
3393 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3396 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3398 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3400 let secp_ctx = Secp256k1::new();
3401 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3402 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3403 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3404 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3405 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3406 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3408 // Send a 0-msat update_add_htlc to fail the channel.
3409 let update_add_htlc = msgs::UpdateAddHTLC {
3415 onion_routing_packet,
3416 skimmed_fee_msat: None,
3418 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3420 let events = nodes[0].node.get_and_clear_pending_events();
3421 assert_eq!(events.len(), 3);
3422 // Check that Alice fails backward the pending HTLC from the second payment.
3424 Event::PaymentPathFailed { payment_hash, .. } => {
3425 assert_eq!(payment_hash, failed_payment_hash);
3427 _ => panic!("Unexpected event"),
3430 Event::PaymentFailed { payment_hash, .. } => {
3431 assert_eq!(payment_hash, failed_payment_hash);
3433 _ => panic!("Unexpected event"),
3436 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3437 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3439 _ => panic!("Unexpected event {:?}", events[1]),
3441 check_closed_broadcast!(nodes[0], true);
3442 check_added_monitors!(nodes[0], 1);
3446 fn test_htlc_ignore_latest_remote_commitment() {
3447 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3448 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3449 let chanmon_cfgs = create_chanmon_cfgs(2);
3450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3451 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3452 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3453 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3454 // We rely on the ability to connect a block redundantly, which isn't allowed via
3455 // `chain::Listen`, so we never run the test if we randomly get assigned that
3459 create_announced_chan_between_nodes(&nodes, 0, 1);
3461 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3462 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3463 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3464 check_closed_broadcast!(nodes[0], true);
3465 check_added_monitors!(nodes[0], 1);
3466 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3468 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3469 assert_eq!(node_txn.len(), 3);
3470 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3472 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3473 connect_block(&nodes[1], &block);
3474 check_closed_broadcast!(nodes[1], true);
3475 check_added_monitors!(nodes[1], 1);
3476 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3478 // Duplicate the connect_block call since this may happen due to other listeners
3479 // registering new transactions
3480 connect_block(&nodes[1], &block);
3484 fn test_force_close_fail_back() {
3485 // Check which HTLCs are failed-backwards on channel force-closure
3486 let chanmon_cfgs = create_chanmon_cfgs(3);
3487 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3488 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3489 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3490 create_announced_chan_between_nodes(&nodes, 0, 1);
3491 create_announced_chan_between_nodes(&nodes, 1, 2);
3493 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3495 let mut payment_event = {
3496 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3497 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3498 check_added_monitors!(nodes[0], 1);
3500 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3501 assert_eq!(events.len(), 1);
3502 SendEvent::from_event(events.remove(0))
3505 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3506 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3508 expect_pending_htlcs_forwardable!(nodes[1]);
3510 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3511 assert_eq!(events_2.len(), 1);
3512 payment_event = SendEvent::from_event(events_2.remove(0));
3513 assert_eq!(payment_event.msgs.len(), 1);
3515 check_added_monitors!(nodes[1], 1);
3516 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3517 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3518 check_added_monitors!(nodes[2], 1);
3519 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3521 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3522 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3523 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3525 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3526 check_closed_broadcast!(nodes[2], true);
3527 check_added_monitors!(nodes[2], 1);
3528 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3530 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3531 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3532 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3533 // back to nodes[1] upon timeout otherwise.
3534 assert_eq!(node_txn.len(), 1);
3538 mine_transaction(&nodes[1], &tx);
3540 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3541 check_closed_broadcast!(nodes[1], true);
3542 check_added_monitors!(nodes[1], 1);
3543 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3545 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3547 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3548 .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);
3550 mine_transaction(&nodes[2], &tx);
3551 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3552 assert_eq!(node_txn.len(), 1);
3553 assert_eq!(node_txn[0].input.len(), 1);
3554 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3555 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3556 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3558 check_spends!(node_txn[0], tx);
3562 fn test_dup_events_on_peer_disconnect() {
3563 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3564 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3565 // as we used to generate the event immediately upon receipt of the payment preimage in the
3566 // update_fulfill_htlc message.
3568 let chanmon_cfgs = create_chanmon_cfgs(2);
3569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3572 create_announced_chan_between_nodes(&nodes, 0, 1);
3574 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3576 nodes[1].node.claim_funds(payment_preimage);
3577 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3578 check_added_monitors!(nodes[1], 1);
3579 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3580 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3581 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3583 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3584 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3586 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3587 expect_payment_path_successful!(nodes[0]);
3591 fn test_peer_disconnected_before_funding_broadcasted() {
3592 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3593 // before the funding transaction has been broadcasted.
3594 let chanmon_cfgs = create_chanmon_cfgs(2);
3595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3597 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3599 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3600 // broadcasted, even though it's created by `nodes[0]`.
3601 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();
3602 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3603 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3604 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3605 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3607 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3608 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3610 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3612 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3613 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3615 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3616 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3619 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3622 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3623 // disconnected before the funding transaction was broadcasted.
3624 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3625 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3627 check_closed_event(&nodes[0], 1, ClosureReason::DisconnectedPeer, false);
3628 check_closed_event(&nodes[1], 1, ClosureReason::DisconnectedPeer, false);
3632 fn test_simple_peer_disconnect() {
3633 // Test that we can reconnect when there are no lost messages
3634 let chanmon_cfgs = create_chanmon_cfgs(3);
3635 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3636 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3637 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3638 create_announced_chan_between_nodes(&nodes, 0, 1);
3639 create_announced_chan_between_nodes(&nodes, 1, 2);
3641 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3642 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3643 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3645 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3646 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3648 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3650 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3651 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3652 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3654 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3655 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3656 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3657 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3659 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3660 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3662 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3663 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3665 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3667 let events = nodes[0].node.get_and_clear_pending_events();
3668 assert_eq!(events.len(), 4);
3670 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3671 assert_eq!(payment_preimage, payment_preimage_3);
3672 assert_eq!(payment_hash, payment_hash_3);
3674 _ => panic!("Unexpected event"),
3677 Event::PaymentPathSuccessful { .. } => {},
3678 _ => panic!("Unexpected event"),
3681 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3682 assert_eq!(payment_hash, payment_hash_5);
3683 assert!(payment_failed_permanently);
3685 _ => panic!("Unexpected event"),
3688 Event::PaymentFailed { payment_hash, .. } => {
3689 assert_eq!(payment_hash, payment_hash_5);
3691 _ => panic!("Unexpected event"),
3695 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3696 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3699 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3700 // Test that we can reconnect when in-flight HTLC updates get dropped
3701 let chanmon_cfgs = create_chanmon_cfgs(2);
3702 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3703 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3704 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3706 let mut as_channel_ready = None;
3707 let channel_id = if messages_delivered == 0 {
3708 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3709 as_channel_ready = Some(channel_ready);
3710 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3711 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3712 // it before the channel_reestablish message.
3715 create_announced_chan_between_nodes(&nodes, 0, 1).2
3718 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3720 let payment_event = {
3721 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3722 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3723 check_added_monitors!(nodes[0], 1);
3725 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3726 assert_eq!(events.len(), 1);
3727 SendEvent::from_event(events.remove(0))
3729 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3731 if messages_delivered < 2 {
3732 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3734 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3735 if messages_delivered >= 3 {
3736 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3737 check_added_monitors!(nodes[1], 1);
3738 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3740 if messages_delivered >= 4 {
3741 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3742 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3743 check_added_monitors!(nodes[0], 1);
3745 if messages_delivered >= 5 {
3746 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3747 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3748 // No commitment_signed so get_event_msg's assert(len == 1) passes
3749 check_added_monitors!(nodes[0], 1);
3751 if messages_delivered >= 6 {
3752 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3753 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3754 check_added_monitors!(nodes[1], 1);
3761 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3762 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3763 if messages_delivered < 3 {
3764 if simulate_broken_lnd {
3765 // lnd has a long-standing bug where they send a channel_ready prior to a
3766 // channel_reestablish if you reconnect prior to channel_ready time.
3768 // Here we simulate that behavior, delivering a channel_ready immediately on
3769 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3770 // in `reconnect_nodes` but we currently don't fail based on that.
3772 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3773 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3775 // Even if the channel_ready messages get exchanged, as long as nothing further was
3776 // received on either side, both sides will need to resend them.
3777 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3778 } else if messages_delivered == 3 {
3779 // nodes[0] still wants its RAA + commitment_signed
3780 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3781 } else if messages_delivered == 4 {
3782 // nodes[0] still wants its commitment_signed
3783 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3784 } else if messages_delivered == 5 {
3785 // nodes[1] still wants its final RAA
3786 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3787 } else if messages_delivered == 6 {
3788 // Everything was delivered...
3789 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3792 let events_1 = nodes[1].node.get_and_clear_pending_events();
3793 if messages_delivered == 0 {
3794 assert_eq!(events_1.len(), 2);
3796 Event::ChannelReady { .. } => { },
3797 _ => panic!("Unexpected event"),
3800 Event::PendingHTLCsForwardable { .. } => { },
3801 _ => panic!("Unexpected event"),
3804 assert_eq!(events_1.len(), 1);
3806 Event::PendingHTLCsForwardable { .. } => { },
3807 _ => panic!("Unexpected event"),
3811 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3812 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815 nodes[1].node.process_pending_htlc_forwards();
3817 let events_2 = nodes[1].node.get_and_clear_pending_events();
3818 assert_eq!(events_2.len(), 1);
3820 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3821 assert_eq!(payment_hash_1, *payment_hash);
3822 assert_eq!(amount_msat, 1_000_000);
3823 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3824 assert_eq!(via_channel_id, Some(channel_id));
3826 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3827 assert!(payment_preimage.is_none());
3828 assert_eq!(payment_secret_1, *payment_secret);
3830 _ => panic!("expected PaymentPurpose::InvoicePayment")
3833 _ => panic!("Unexpected event"),
3836 nodes[1].node.claim_funds(payment_preimage_1);
3837 check_added_monitors!(nodes[1], 1);
3838 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3840 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3841 assert_eq!(events_3.len(), 1);
3842 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3843 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3844 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3845 assert!(updates.update_add_htlcs.is_empty());
3846 assert!(updates.update_fail_htlcs.is_empty());
3847 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3848 assert!(updates.update_fail_malformed_htlcs.is_empty());
3849 assert!(updates.update_fee.is_none());
3850 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3852 _ => panic!("Unexpected event"),
3855 if messages_delivered >= 1 {
3856 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3858 let events_4 = nodes[0].node.get_and_clear_pending_events();
3859 assert_eq!(events_4.len(), 1);
3861 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3862 assert_eq!(payment_preimage_1, *payment_preimage);
3863 assert_eq!(payment_hash_1, *payment_hash);
3865 _ => panic!("Unexpected event"),
3868 if messages_delivered >= 2 {
3869 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3870 check_added_monitors!(nodes[0], 1);
3871 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3873 if messages_delivered >= 3 {
3874 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3875 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3876 check_added_monitors!(nodes[1], 1);
3878 if messages_delivered >= 4 {
3879 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3880 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3881 // No commitment_signed so get_event_msg's assert(len == 1) passes
3882 check_added_monitors!(nodes[1], 1);
3884 if messages_delivered >= 5 {
3885 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3886 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3887 check_added_monitors!(nodes[0], 1);
3894 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3895 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3896 if messages_delivered < 2 {
3897 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3898 if messages_delivered < 1 {
3899 expect_payment_sent!(nodes[0], payment_preimage_1);
3901 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3903 } else if messages_delivered == 2 {
3904 // nodes[0] still wants its RAA + commitment_signed
3905 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3906 } else if messages_delivered == 3 {
3907 // nodes[0] still wants its commitment_signed
3908 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3909 } else if messages_delivered == 4 {
3910 // nodes[1] still wants its final RAA
3911 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3912 } else if messages_delivered == 5 {
3913 // Everything was delivered...
3914 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3917 if messages_delivered == 1 || messages_delivered == 2 {
3918 expect_payment_path_successful!(nodes[0]);
3920 if messages_delivered <= 5 {
3921 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3922 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3924 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3926 if messages_delivered > 2 {
3927 expect_payment_path_successful!(nodes[0]);
3930 // Channel should still work fine...
3931 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3932 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3933 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3937 fn test_drop_messages_peer_disconnect_a() {
3938 do_test_drop_messages_peer_disconnect(0, true);
3939 do_test_drop_messages_peer_disconnect(0, false);
3940 do_test_drop_messages_peer_disconnect(1, false);
3941 do_test_drop_messages_peer_disconnect(2, false);
3945 fn test_drop_messages_peer_disconnect_b() {
3946 do_test_drop_messages_peer_disconnect(3, false);
3947 do_test_drop_messages_peer_disconnect(4, false);
3948 do_test_drop_messages_peer_disconnect(5, false);
3949 do_test_drop_messages_peer_disconnect(6, false);
3953 fn test_channel_ready_without_best_block_updated() {
3954 // Previously, if we were offline when a funding transaction was locked in, and then we came
3955 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3956 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3957 // channel_ready immediately instead.
3958 let chanmon_cfgs = create_chanmon_cfgs(2);
3959 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3960 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3961 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3962 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3964 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3966 let conf_height = nodes[0].best_block_info().1 + 1;
3967 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3968 let block_txn = [funding_tx];
3969 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3970 let conf_block_header = nodes[0].get_block_header(conf_height);
3971 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3973 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3974 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3975 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3979 fn test_drop_messages_peer_disconnect_dual_htlc() {
3980 // Test that we can handle reconnecting when both sides of a channel have pending
3981 // commitment_updates when we disconnect.
3982 let chanmon_cfgs = create_chanmon_cfgs(2);
3983 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3984 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3985 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3986 create_announced_chan_between_nodes(&nodes, 0, 1);
3988 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3990 // Now try to send a second payment which will fail to send
3991 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3992 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3993 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3994 check_added_monitors!(nodes[0], 1);
3996 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3997 assert_eq!(events_1.len(), 1);
3999 MessageSendEvent::UpdateHTLCs { .. } => {},
4000 _ => panic!("Unexpected event"),
4003 nodes[1].node.claim_funds(payment_preimage_1);
4004 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4005 check_added_monitors!(nodes[1], 1);
4007 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4008 assert_eq!(events_2.len(), 1);
4010 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 } } => {
4011 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4012 assert!(update_add_htlcs.is_empty());
4013 assert_eq!(update_fulfill_htlcs.len(), 1);
4014 assert!(update_fail_htlcs.is_empty());
4015 assert!(update_fail_malformed_htlcs.is_empty());
4016 assert!(update_fee.is_none());
4018 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4019 let events_3 = nodes[0].node.get_and_clear_pending_events();
4020 assert_eq!(events_3.len(), 1);
4022 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4023 assert_eq!(*payment_preimage, payment_preimage_1);
4024 assert_eq!(*payment_hash, payment_hash_1);
4026 _ => panic!("Unexpected event"),
4029 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4030 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4031 // No commitment_signed so get_event_msg's assert(len == 1) passes
4032 check_added_monitors!(nodes[0], 1);
4034 _ => panic!("Unexpected event"),
4037 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4038 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4040 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4041 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4043 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4044 assert_eq!(reestablish_1.len(), 1);
4045 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4046 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4048 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4049 assert_eq!(reestablish_2.len(), 1);
4051 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4052 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4053 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4054 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4056 assert!(as_resp.0.is_none());
4057 assert!(bs_resp.0.is_none());
4059 assert!(bs_resp.1.is_none());
4060 assert!(bs_resp.2.is_none());
4062 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4064 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4065 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4066 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4067 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4068 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4069 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4071 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4072 // No commitment_signed so get_event_msg's assert(len == 1) passes
4073 check_added_monitors!(nodes[1], 1);
4075 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4076 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4077 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4078 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4079 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4080 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4081 assert!(bs_second_commitment_signed.update_fee.is_none());
4082 check_added_monitors!(nodes[1], 1);
4084 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4085 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4086 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4087 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4088 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4089 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4090 assert!(as_commitment_signed.update_fee.is_none());
4091 check_added_monitors!(nodes[0], 1);
4093 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4094 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4095 // No commitment_signed so get_event_msg's assert(len == 1) passes
4096 check_added_monitors!(nodes[0], 1);
4098 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4099 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4100 // No commitment_signed so get_event_msg's assert(len == 1) passes
4101 check_added_monitors!(nodes[1], 1);
4103 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4104 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4105 check_added_monitors!(nodes[1], 1);
4107 expect_pending_htlcs_forwardable!(nodes[1]);
4109 let events_5 = nodes[1].node.get_and_clear_pending_events();
4110 assert_eq!(events_5.len(), 1);
4112 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4113 assert_eq!(payment_hash_2, *payment_hash);
4115 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4116 assert!(payment_preimage.is_none());
4117 assert_eq!(payment_secret_2, *payment_secret);
4119 _ => panic!("expected PaymentPurpose::InvoicePayment")
4122 _ => panic!("Unexpected event"),
4125 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4126 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4127 check_added_monitors!(nodes[0], 1);
4129 expect_payment_path_successful!(nodes[0]);
4130 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4133 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4134 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4135 // to avoid our counterparty failing the channel.
4136 let chanmon_cfgs = create_chanmon_cfgs(2);
4137 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4138 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4139 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4141 create_announced_chan_between_nodes(&nodes, 0, 1);
4143 let our_payment_hash = if send_partial_mpp {
4144 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4145 // Use the utility function send_payment_along_path to send the payment with MPP data which
4146 // indicates there are more HTLCs coming.
4147 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.
4148 let payment_id = PaymentId([42; 32]);
4149 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4150 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4151 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4152 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4153 &None, session_privs[0]).unwrap();
4154 check_added_monitors!(nodes[0], 1);
4155 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4156 assert_eq!(events.len(), 1);
4157 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4158 // hop should *not* yet generate any PaymentClaimable event(s).
4159 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4162 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4165 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4166 connect_block(&nodes[0], &block);
4167 connect_block(&nodes[1], &block);
4168 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4169 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4170 block.header.prev_blockhash = block.block_hash();
4171 connect_block(&nodes[0], &block);
4172 connect_block(&nodes[1], &block);
4175 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4177 check_added_monitors!(nodes[1], 1);
4178 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4179 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4180 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4181 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4182 assert!(htlc_timeout_updates.update_fee.is_none());
4184 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4185 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4186 // 100_000 msat as u64, followed by the height at which we failed back above
4187 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4188 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4189 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4193 fn test_htlc_timeout() {
4194 do_test_htlc_timeout(true);
4195 do_test_htlc_timeout(false);
4198 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4199 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4200 let chanmon_cfgs = create_chanmon_cfgs(3);
4201 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4202 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4203 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4204 create_announced_chan_between_nodes(&nodes, 0, 1);
4205 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4207 // Make sure all nodes are at the same starting height
4208 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4209 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4210 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4212 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4213 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4214 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4215 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4216 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4217 check_added_monitors!(nodes[1], 1);
4219 // Now attempt to route a second payment, which should be placed in the holding cell
4220 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4221 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4222 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4223 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4225 check_added_monitors!(nodes[0], 1);
4226 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4227 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4228 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4229 expect_pending_htlcs_forwardable!(nodes[1]);
4231 check_added_monitors!(nodes[1], 0);
4233 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4234 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4235 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4236 connect_blocks(&nodes[1], 1);
4239 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 }]);
4240 check_added_monitors!(nodes[1], 1);
4241 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4242 assert_eq!(fail_commit.len(), 1);
4243 match fail_commit[0] {
4244 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4246 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4248 _ => unreachable!(),
4250 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4252 expect_payment_failed!(nodes[1], second_payment_hash, false);
4257 fn test_holding_cell_htlc_add_timeouts() {
4258 do_test_holding_cell_htlc_add_timeouts(false);
4259 do_test_holding_cell_htlc_add_timeouts(true);
4262 macro_rules! check_spendable_outputs {
4263 ($node: expr, $keysinterface: expr) => {
4265 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4266 let mut txn = Vec::new();
4267 let mut all_outputs = Vec::new();
4268 let secp_ctx = Secp256k1::new();
4269 for event in events.drain(..) {
4271 Event::SpendableOutputs { mut outputs } => {
4272 for outp in outputs.drain(..) {
4273 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4274 all_outputs.push(outp);
4277 _ => panic!("Unexpected event"),
4280 if all_outputs.len() > 1 {
4281 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, None, &secp_ctx) {
4291 fn test_claim_sizeable_push_msat() {
4292 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4293 let chanmon_cfgs = create_chanmon_cfgs(2);
4294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4296 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4298 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4299 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4300 check_closed_broadcast!(nodes[1], true);
4301 check_added_monitors!(nodes[1], 1);
4302 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4303 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4304 assert_eq!(node_txn.len(), 1);
4305 check_spends!(node_txn[0], chan.3);
4306 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
4308 mine_transaction(&nodes[1], &node_txn[0]);
4309 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4311 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4312 assert_eq!(spend_txn.len(), 1);
4313 assert_eq!(spend_txn[0].input.len(), 1);
4314 check_spends!(spend_txn[0], node_txn[0]);
4315 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4319 fn test_claim_on_remote_sizeable_push_msat() {
4320 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4321 // to_remote output is encumbered by a P2WPKH
4322 let chanmon_cfgs = create_chanmon_cfgs(2);
4323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4325 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4327 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4328 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4329 check_closed_broadcast!(nodes[0], true);
4330 check_added_monitors!(nodes[0], 1);
4331 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4333 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4334 assert_eq!(node_txn.len(), 1);
4335 check_spends!(node_txn[0], chan.3);
4336 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
4338 mine_transaction(&nodes[1], &node_txn[0]);
4339 check_closed_broadcast!(nodes[1], true);
4340 check_added_monitors!(nodes[1], 1);
4341 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4342 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4344 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4345 assert_eq!(spend_txn.len(), 1);
4346 check_spends!(spend_txn[0], node_txn[0]);
4350 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4351 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4352 // to_remote output is encumbered by a P2WPKH
4354 let chanmon_cfgs = create_chanmon_cfgs(2);
4355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4357 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4359 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4360 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4361 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4362 assert_eq!(revoked_local_txn[0].input.len(), 1);
4363 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4365 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4366 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4367 check_closed_broadcast!(nodes[1], true);
4368 check_added_monitors!(nodes[1], 1);
4369 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4371 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4372 mine_transaction(&nodes[1], &node_txn[0]);
4373 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4375 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4376 assert_eq!(spend_txn.len(), 3);
4377 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4378 check_spends!(spend_txn[1], node_txn[0]);
4379 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4383 fn test_static_spendable_outputs_preimage_tx() {
4384 let chanmon_cfgs = create_chanmon_cfgs(2);
4385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4387 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4389 // Create some initial channels
4390 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4392 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4394 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4395 assert_eq!(commitment_tx[0].input.len(), 1);
4396 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4398 // Settle A's commitment tx on B's chain
4399 nodes[1].node.claim_funds(payment_preimage);
4400 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4401 check_added_monitors!(nodes[1], 1);
4402 mine_transaction(&nodes[1], &commitment_tx[0]);
4403 check_added_monitors!(nodes[1], 1);
4404 let events = nodes[1].node.get_and_clear_pending_msg_events();
4406 MessageSendEvent::UpdateHTLCs { .. } => {},
4407 _ => panic!("Unexpected event"),
4410 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4411 _ => panic!("Unexepected event"),
4414 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4415 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4416 assert_eq!(node_txn.len(), 1);
4417 check_spends!(node_txn[0], commitment_tx[0]);
4418 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4420 mine_transaction(&nodes[1], &node_txn[0]);
4421 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4422 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4424 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4425 assert_eq!(spend_txn.len(), 1);
4426 check_spends!(spend_txn[0], node_txn[0]);
4430 fn test_static_spendable_outputs_timeout_tx() {
4431 let chanmon_cfgs = create_chanmon_cfgs(2);
4432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4434 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4436 // Create some initial channels
4437 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4439 // Rebalance the network a bit by relaying one payment through all the channels ...
4440 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4442 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4444 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4445 assert_eq!(commitment_tx[0].input.len(), 1);
4446 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4448 // Settle A's commitment tx on B' chain
4449 mine_transaction(&nodes[1], &commitment_tx[0]);
4450 check_added_monitors!(nodes[1], 1);
4451 let events = nodes[1].node.get_and_clear_pending_msg_events();
4453 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4454 _ => panic!("Unexpected event"),
4456 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4458 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4459 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4460 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4461 check_spends!(node_txn[0], commitment_tx[0].clone());
4462 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4464 mine_transaction(&nodes[1], &node_txn[0]);
4465 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4466 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4467 expect_payment_failed!(nodes[1], our_payment_hash, false);
4469 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4470 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4471 check_spends!(spend_txn[0], commitment_tx[0]);
4472 check_spends!(spend_txn[1], node_txn[0]);
4473 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4477 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4478 let chanmon_cfgs = create_chanmon_cfgs(2);
4479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4483 // Create some initial channels
4484 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4486 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4487 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4488 assert_eq!(revoked_local_txn[0].input.len(), 1);
4489 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4491 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4493 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4494 check_closed_broadcast!(nodes[1], true);
4495 check_added_monitors!(nodes[1], 1);
4496 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4498 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4499 assert_eq!(node_txn.len(), 1);
4500 assert_eq!(node_txn[0].input.len(), 2);
4501 check_spends!(node_txn[0], revoked_local_txn[0]);
4503 mine_transaction(&nodes[1], &node_txn[0]);
4504 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4506 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4507 assert_eq!(spend_txn.len(), 1);
4508 check_spends!(spend_txn[0], node_txn[0]);
4512 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4513 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4514 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4519 // Create some initial channels
4520 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4522 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4523 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4524 assert_eq!(revoked_local_txn[0].input.len(), 1);
4525 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4527 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4529 // A will generate HTLC-Timeout from revoked commitment tx
4530 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4531 check_closed_broadcast!(nodes[0], true);
4532 check_added_monitors!(nodes[0], 1);
4533 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4534 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4536 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4537 assert_eq!(revoked_htlc_txn.len(), 1);
4538 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4539 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4540 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4541 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4543 // B will generate justice tx from A's revoked commitment/HTLC tx
4544 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4545 check_closed_broadcast!(nodes[1], true);
4546 check_added_monitors!(nodes[1], 1);
4547 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4549 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4550 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4551 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4552 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4553 // transactions next...
4554 assert_eq!(node_txn[0].input.len(), 3);
4555 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4557 assert_eq!(node_txn[1].input.len(), 2);
4558 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4559 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4560 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4562 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4563 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4566 mine_transaction(&nodes[1], &node_txn[1]);
4567 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4569 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4570 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4571 assert_eq!(spend_txn.len(), 1);
4572 assert_eq!(spend_txn[0].input.len(), 1);
4573 check_spends!(spend_txn[0], node_txn[1]);
4577 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4578 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4579 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4582 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4584 // Create some initial channels
4585 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4587 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4588 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4589 assert_eq!(revoked_local_txn[0].input.len(), 1);
4590 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4592 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4593 assert_eq!(revoked_local_txn[0].output.len(), 2);
4595 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4597 // B will generate HTLC-Success from revoked commitment tx
4598 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4599 check_closed_broadcast!(nodes[1], true);
4600 check_added_monitors!(nodes[1], 1);
4601 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4602 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4604 assert_eq!(revoked_htlc_txn.len(), 1);
4605 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4606 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4607 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4609 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4610 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4611 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4613 // A will generate justice tx from B's revoked commitment/HTLC tx
4614 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4615 check_closed_broadcast!(nodes[0], true);
4616 check_added_monitors!(nodes[0], 1);
4617 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4619 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4620 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4622 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4623 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4624 // transactions next...
4625 assert_eq!(node_txn[0].input.len(), 2);
4626 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4627 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4628 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4630 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4631 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4634 assert_eq!(node_txn[1].input.len(), 1);
4635 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4637 mine_transaction(&nodes[0], &node_txn[1]);
4638 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4640 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4641 // didn't try to generate any new transactions.
4643 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4644 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4645 assert_eq!(spend_txn.len(), 3);
4646 assert_eq!(spend_txn[0].input.len(), 1);
4647 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4648 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4649 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4650 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4654 fn test_onchain_to_onchain_claim() {
4655 // Test that in case of channel closure, we detect the state of output and claim HTLC
4656 // on downstream peer's remote commitment tx.
4657 // First, have C claim an HTLC against its own latest commitment transaction.
4658 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4660 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4663 let chanmon_cfgs = create_chanmon_cfgs(3);
4664 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4665 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4666 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4668 // Create some initial channels
4669 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4670 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4672 // Ensure all nodes are at the same height
4673 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4674 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4675 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4676 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4678 // Rebalance the network a bit by relaying one payment through all the channels ...
4679 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4680 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4682 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4683 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4684 check_spends!(commitment_tx[0], chan_2.3);
4685 nodes[2].node.claim_funds(payment_preimage);
4686 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4687 check_added_monitors!(nodes[2], 1);
4688 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4689 assert!(updates.update_add_htlcs.is_empty());
4690 assert!(updates.update_fail_htlcs.is_empty());
4691 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4692 assert!(updates.update_fail_malformed_htlcs.is_empty());
4694 mine_transaction(&nodes[2], &commitment_tx[0]);
4695 check_closed_broadcast!(nodes[2], true);
4696 check_added_monitors!(nodes[2], 1);
4697 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4699 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4700 assert_eq!(c_txn.len(), 1);
4701 check_spends!(c_txn[0], commitment_tx[0]);
4702 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4703 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4704 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4706 // 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
4707 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4708 check_added_monitors!(nodes[1], 1);
4709 let events = nodes[1].node.get_and_clear_pending_events();
4710 assert_eq!(events.len(), 2);
4712 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4713 _ => panic!("Unexpected event"),
4716 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4717 assert_eq!(fee_earned_msat, Some(1000));
4718 assert_eq!(prev_channel_id, Some(chan_1.2));
4719 assert_eq!(claim_from_onchain_tx, true);
4720 assert_eq!(next_channel_id, Some(chan_2.2));
4721 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4723 _ => panic!("Unexpected event"),
4725 check_added_monitors!(nodes[1], 1);
4726 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4727 assert_eq!(msg_events.len(), 3);
4728 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4729 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4731 match nodes_2_event {
4732 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4733 _ => panic!("Unexpected event"),
4736 match nodes_0_event {
4737 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, .. } } => {
4738 assert!(update_add_htlcs.is_empty());
4739 assert!(update_fail_htlcs.is_empty());
4740 assert_eq!(update_fulfill_htlcs.len(), 1);
4741 assert!(update_fail_malformed_htlcs.is_empty());
4742 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4744 _ => panic!("Unexpected event"),
4747 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4748 match msg_events[0] {
4749 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4750 _ => panic!("Unexpected event"),
4753 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4754 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4755 mine_transaction(&nodes[1], &commitment_tx[0]);
4756 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4757 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4758 // ChannelMonitor: HTLC-Success tx
4759 assert_eq!(b_txn.len(), 1);
4760 check_spends!(b_txn[0], commitment_tx[0]);
4761 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4762 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4763 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4765 check_closed_broadcast!(nodes[1], true);
4766 check_added_monitors!(nodes[1], 1);
4770 fn test_duplicate_payment_hash_one_failure_one_success() {
4771 // Topology : A --> B --> C --> D
4772 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4773 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4774 // we forward one of the payments onwards to D.
4775 let chanmon_cfgs = create_chanmon_cfgs(4);
4776 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4777 // When this test was written, the default base fee floated based on the HTLC count.
4778 // It is now fixed, so we simply set the fee to the expected value here.
4779 let mut config = test_default_channel_config();
4780 config.channel_config.forwarding_fee_base_msat = 196;
4781 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4782 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4783 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4785 create_announced_chan_between_nodes(&nodes, 0, 1);
4786 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4787 create_announced_chan_between_nodes(&nodes, 2, 3);
4789 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4790 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4791 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4792 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4793 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4795 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4797 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4798 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4799 // script push size limit so that the below script length checks match
4800 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4801 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4802 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4803 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4804 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4806 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4807 assert_eq!(commitment_txn[0].input.len(), 1);
4808 check_spends!(commitment_txn[0], chan_2.3);
4810 mine_transaction(&nodes[1], &commitment_txn[0]);
4811 check_closed_broadcast!(nodes[1], true);
4812 check_added_monitors!(nodes[1], 1);
4813 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4814 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4816 let htlc_timeout_tx;
4817 { // Extract one of the two HTLC-Timeout transaction
4818 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4819 // ChannelMonitor: timeout tx * 2-or-3
4820 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4822 check_spends!(node_txn[0], commitment_txn[0]);
4823 assert_eq!(node_txn[0].input.len(), 1);
4824 assert_eq!(node_txn[0].output.len(), 1);
4826 if node_txn.len() > 2 {
4827 check_spends!(node_txn[1], commitment_txn[0]);
4828 assert_eq!(node_txn[1].input.len(), 1);
4829 assert_eq!(node_txn[1].output.len(), 1);
4830 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4832 check_spends!(node_txn[2], commitment_txn[0]);
4833 assert_eq!(node_txn[2].input.len(), 1);
4834 assert_eq!(node_txn[2].output.len(), 1);
4835 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4837 check_spends!(node_txn[1], commitment_txn[0]);
4838 assert_eq!(node_txn[1].input.len(), 1);
4839 assert_eq!(node_txn[1].output.len(), 1);
4840 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4843 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4844 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4845 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4846 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4847 if node_txn.len() > 2 {
4848 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4849 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4851 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4855 nodes[2].node.claim_funds(our_payment_preimage);
4856 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4858 mine_transaction(&nodes[2], &commitment_txn[0]);
4859 check_added_monitors!(nodes[2], 2);
4860 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4861 let events = nodes[2].node.get_and_clear_pending_msg_events();
4863 MessageSendEvent::UpdateHTLCs { .. } => {},
4864 _ => panic!("Unexpected event"),
4867 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4868 _ => panic!("Unexepected event"),
4870 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4871 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4872 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4873 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4874 assert_eq!(htlc_success_txn[0].input.len(), 1);
4875 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4876 assert_eq!(htlc_success_txn[1].input.len(), 1);
4877 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4878 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4879 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4881 mine_transaction(&nodes[1], &htlc_timeout_tx);
4882 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4883 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 }]);
4884 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4885 assert!(htlc_updates.update_add_htlcs.is_empty());
4886 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4887 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4888 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4889 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4890 check_added_monitors!(nodes[1], 1);
4892 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4893 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4895 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4897 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4899 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4900 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4901 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4902 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4903 assert!(updates.update_add_htlcs.is_empty());
4904 assert!(updates.update_fail_htlcs.is_empty());
4905 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4906 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4907 assert!(updates.update_fail_malformed_htlcs.is_empty());
4908 check_added_monitors!(nodes[1], 1);
4910 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4911 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4912 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4916 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4917 let chanmon_cfgs = create_chanmon_cfgs(2);
4918 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4919 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4920 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4922 // Create some initial channels
4923 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4925 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4926 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4927 assert_eq!(local_txn.len(), 1);
4928 assert_eq!(local_txn[0].input.len(), 1);
4929 check_spends!(local_txn[0], chan_1.3);
4931 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4932 nodes[1].node.claim_funds(payment_preimage);
4933 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4934 check_added_monitors!(nodes[1], 1);
4936 mine_transaction(&nodes[1], &local_txn[0]);
4937 check_added_monitors!(nodes[1], 1);
4938 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4939 let events = nodes[1].node.get_and_clear_pending_msg_events();
4941 MessageSendEvent::UpdateHTLCs { .. } => {},
4942 _ => panic!("Unexpected event"),
4945 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4946 _ => panic!("Unexepected event"),
4949 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4950 assert_eq!(node_txn.len(), 1);
4951 assert_eq!(node_txn[0].input.len(), 1);
4952 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4953 check_spends!(node_txn[0], local_txn[0]);
4957 mine_transaction(&nodes[1], &node_tx);
4958 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4960 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4961 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4962 assert_eq!(spend_txn.len(), 1);
4963 assert_eq!(spend_txn[0].input.len(), 1);
4964 check_spends!(spend_txn[0], node_tx);
4965 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4968 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4969 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4970 // unrevoked commitment transaction.
4971 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4972 // a remote RAA before they could be failed backwards (and combinations thereof).
4973 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4974 // use the same payment hashes.
4975 // Thus, we use a six-node network:
4980 // And test where C fails back to A/B when D announces its latest commitment transaction
4981 let chanmon_cfgs = create_chanmon_cfgs(6);
4982 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4983 // When this test was written, the default base fee floated based on the HTLC count.
4984 // It is now fixed, so we simply set the fee to the expected value here.
4985 let mut config = test_default_channel_config();
4986 config.channel_config.forwarding_fee_base_msat = 196;
4987 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4988 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4989 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4991 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4992 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4993 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4994 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4995 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4997 // Rebalance and check output sanity...
4998 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4999 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5000 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5002 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5003 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context.holder_dust_limit_satoshis;
5005 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
5007 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
5008 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5010 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
5012 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
5014 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5016 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5017 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5019 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());
5021 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());
5024 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5026 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5027 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
5030 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
5032 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5033 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());
5035 // Double-check that six of the new HTLC were added
5036 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5037 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5038 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5039 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5041 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5042 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5043 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5044 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5045 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5046 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5047 check_added_monitors!(nodes[4], 0);
5049 let failed_destinations = vec![
5050 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5051 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5052 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5053 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5055 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5056 check_added_monitors!(nodes[4], 1);
5058 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5059 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5060 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5061 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5062 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5063 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5065 // Fail 3rd below-dust and 7th above-dust HTLCs
5066 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5067 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5068 check_added_monitors!(nodes[5], 0);
5070 let failed_destinations_2 = vec![
5071 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5072 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5074 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5075 check_added_monitors!(nodes[5], 1);
5077 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5078 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5079 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5080 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5082 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5084 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5085 let failed_destinations_3 = vec![
5086 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5087 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5088 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5089 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5090 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5091 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5093 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5094 check_added_monitors!(nodes[3], 1);
5095 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5096 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5097 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5098 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5099 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5100 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5101 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5102 if deliver_last_raa {
5103 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5105 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5108 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5109 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5110 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5111 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5113 // We now broadcast the latest commitment transaction, which *should* result in failures for
5114 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5115 // the non-broadcast above-dust HTLCs.
5117 // Alternatively, we may broadcast the previous commitment transaction, which should only
5118 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5119 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5121 if announce_latest {
5122 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5124 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5126 let events = nodes[2].node.get_and_clear_pending_events();
5127 let close_event = if deliver_last_raa {
5128 assert_eq!(events.len(), 2 + 6);
5129 events.last().clone().unwrap()
5131 assert_eq!(events.len(), 1);
5132 events.last().clone().unwrap()
5135 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5136 _ => panic!("Unexpected event"),
5139 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5140 check_closed_broadcast!(nodes[2], true);
5141 if deliver_last_raa {
5142 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5144 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();
5145 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5147 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5148 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5150 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5153 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5155 check_added_monitors!(nodes[2], 3);
5157 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5158 assert_eq!(cs_msgs.len(), 2);
5159 let mut a_done = false;
5160 for msg in cs_msgs {
5162 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5163 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5164 // should be failed-backwards here.
5165 let target = if *node_id == nodes[0].node.get_our_node_id() {
5166 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5167 for htlc in &updates.update_fail_htlcs {
5168 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 });
5170 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5175 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5176 for htlc in &updates.update_fail_htlcs {
5177 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5179 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5180 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5183 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5184 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5185 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5186 if announce_latest {
5187 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5188 if *node_id == nodes[0].node.get_our_node_id() {
5189 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5192 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5194 _ => panic!("Unexpected event"),
5198 let as_events = nodes[0].node.get_and_clear_pending_events();
5199 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5200 let mut as_failds = HashSet::new();
5201 let mut as_updates = 0;
5202 for event in as_events.iter() {
5203 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5204 assert!(as_failds.insert(*payment_hash));
5205 if *payment_hash != payment_hash_2 {
5206 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5208 assert!(!payment_failed_permanently);
5210 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5213 } else if let &Event::PaymentFailed { .. } = event {
5214 } else { panic!("Unexpected event"); }
5216 assert!(as_failds.contains(&payment_hash_1));
5217 assert!(as_failds.contains(&payment_hash_2));
5218 if announce_latest {
5219 assert!(as_failds.contains(&payment_hash_3));
5220 assert!(as_failds.contains(&payment_hash_5));
5222 assert!(as_failds.contains(&payment_hash_6));
5224 let bs_events = nodes[1].node.get_and_clear_pending_events();
5225 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5226 let mut bs_failds = HashSet::new();
5227 let mut bs_updates = 0;
5228 for event in bs_events.iter() {
5229 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5230 assert!(bs_failds.insert(*payment_hash));
5231 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5232 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5234 assert!(!payment_failed_permanently);
5236 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5239 } else if let &Event::PaymentFailed { .. } = event {
5240 } else { panic!("Unexpected event"); }
5242 assert!(bs_failds.contains(&payment_hash_1));
5243 assert!(bs_failds.contains(&payment_hash_2));
5244 if announce_latest {
5245 assert!(bs_failds.contains(&payment_hash_4));
5247 assert!(bs_failds.contains(&payment_hash_5));
5249 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5250 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5251 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5252 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5253 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5254 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5258 fn test_fail_backwards_latest_remote_announce_a() {
5259 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5263 fn test_fail_backwards_latest_remote_announce_b() {
5264 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5268 fn test_fail_backwards_previous_remote_announce() {
5269 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5270 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5271 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5275 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5276 let chanmon_cfgs = create_chanmon_cfgs(2);
5277 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5278 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5279 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5281 // Create some initial channels
5282 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5284 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5285 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5286 assert_eq!(local_txn[0].input.len(), 1);
5287 check_spends!(local_txn[0], chan_1.3);
5289 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5290 mine_transaction(&nodes[0], &local_txn[0]);
5291 check_closed_broadcast!(nodes[0], true);
5292 check_added_monitors!(nodes[0], 1);
5293 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5294 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5296 let htlc_timeout = {
5297 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5298 assert_eq!(node_txn.len(), 1);
5299 assert_eq!(node_txn[0].input.len(), 1);
5300 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5301 check_spends!(node_txn[0], local_txn[0]);
5305 mine_transaction(&nodes[0], &htlc_timeout);
5306 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5307 expect_payment_failed!(nodes[0], our_payment_hash, false);
5309 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5310 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5311 assert_eq!(spend_txn.len(), 3);
5312 check_spends!(spend_txn[0], local_txn[0]);
5313 assert_eq!(spend_txn[1].input.len(), 1);
5314 check_spends!(spend_txn[1], htlc_timeout);
5315 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5316 assert_eq!(spend_txn[2].input.len(), 2);
5317 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5318 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5319 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5323 fn test_key_derivation_params() {
5324 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5325 // manager rotation to test that `channel_keys_id` returned in
5326 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5327 // then derive a `delayed_payment_key`.
5329 let chanmon_cfgs = create_chanmon_cfgs(3);
5331 // We manually create the node configuration to backup the seed.
5332 let seed = [42; 32];
5333 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5334 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);
5335 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5336 let scorer = Mutex::new(test_utils::TestScorer::new());
5337 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5338 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)) };
5339 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5340 node_cfgs.remove(0);
5341 node_cfgs.insert(0, node);
5343 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5344 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5346 // Create some initial channels
5347 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5349 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5350 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5351 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5353 // Ensure all nodes are at the same height
5354 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5355 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5356 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5357 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5359 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5360 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5361 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5362 assert_eq!(local_txn_1[0].input.len(), 1);
5363 check_spends!(local_txn_1[0], chan_1.3);
5365 // We check funding pubkey are unique
5366 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]));
5367 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]));
5368 if from_0_funding_key_0 == from_1_funding_key_0
5369 || from_0_funding_key_0 == from_1_funding_key_1
5370 || from_0_funding_key_1 == from_1_funding_key_0
5371 || from_0_funding_key_1 == from_1_funding_key_1 {
5372 panic!("Funding pubkeys aren't unique");
5375 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5376 mine_transaction(&nodes[0], &local_txn_1[0]);
5377 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5378 check_closed_broadcast!(nodes[0], true);
5379 check_added_monitors!(nodes[0], 1);
5380 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5382 let htlc_timeout = {
5383 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5384 assert_eq!(node_txn.len(), 1);
5385 assert_eq!(node_txn[0].input.len(), 1);
5386 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5387 check_spends!(node_txn[0], local_txn_1[0]);
5391 mine_transaction(&nodes[0], &htlc_timeout);
5392 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5393 expect_payment_failed!(nodes[0], our_payment_hash, false);
5395 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5396 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5397 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5398 assert_eq!(spend_txn.len(), 3);
5399 check_spends!(spend_txn[0], local_txn_1[0]);
5400 assert_eq!(spend_txn[1].input.len(), 1);
5401 check_spends!(spend_txn[1], htlc_timeout);
5402 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5403 assert_eq!(spend_txn[2].input.len(), 2);
5404 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5405 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5406 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5410 fn test_static_output_closing_tx() {
5411 let chanmon_cfgs = create_chanmon_cfgs(2);
5412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5414 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5416 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5418 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5419 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5421 mine_transaction(&nodes[0], &closing_tx);
5422 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5423 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5425 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5426 assert_eq!(spend_txn.len(), 1);
5427 check_spends!(spend_txn[0], closing_tx);
5429 mine_transaction(&nodes[1], &closing_tx);
5430 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5431 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5433 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5434 assert_eq!(spend_txn.len(), 1);
5435 check_spends!(spend_txn[0], closing_tx);
5438 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5439 let chanmon_cfgs = create_chanmon_cfgs(2);
5440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5443 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5445 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5447 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5448 // present in B's local commitment transaction, but none of A's commitment transactions.
5449 nodes[1].node.claim_funds(payment_preimage);
5450 check_added_monitors!(nodes[1], 1);
5451 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5453 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5454 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5455 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5457 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5458 check_added_monitors!(nodes[0], 1);
5459 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5460 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5461 check_added_monitors!(nodes[1], 1);
5463 let starting_block = nodes[1].best_block_info();
5464 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5465 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5466 connect_block(&nodes[1], &block);
5467 block.header.prev_blockhash = block.block_hash();
5469 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5470 check_closed_broadcast!(nodes[1], true);
5471 check_added_monitors!(nodes[1], 1);
5472 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5475 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5476 let chanmon_cfgs = create_chanmon_cfgs(2);
5477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5480 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5482 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5483 nodes[0].node.send_payment_with_route(&route, payment_hash,
5484 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5485 check_added_monitors!(nodes[0], 1);
5487 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5489 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5490 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5491 // to "time out" the HTLC.
5493 let starting_block = nodes[1].best_block_info();
5494 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5496 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5497 connect_block(&nodes[0], &block);
5498 block.header.prev_blockhash = block.block_hash();
5500 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5501 check_closed_broadcast!(nodes[0], true);
5502 check_added_monitors!(nodes[0], 1);
5503 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5506 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5507 let chanmon_cfgs = create_chanmon_cfgs(3);
5508 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5509 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5510 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5511 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5513 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5514 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5515 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5516 // actually revoked.
5517 let htlc_value = if use_dust { 50000 } else { 3000000 };
5518 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5519 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5520 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5521 check_added_monitors!(nodes[1], 1);
5523 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5524 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5525 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5526 check_added_monitors!(nodes[0], 1);
5527 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5528 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5529 check_added_monitors!(nodes[1], 1);
5530 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5531 check_added_monitors!(nodes[1], 1);
5532 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5534 if check_revoke_no_close {
5535 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5536 check_added_monitors!(nodes[0], 1);
5539 let starting_block = nodes[1].best_block_info();
5540 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5541 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5542 connect_block(&nodes[0], &block);
5543 block.header.prev_blockhash = block.block_hash();
5545 if !check_revoke_no_close {
5546 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5547 check_closed_broadcast!(nodes[0], true);
5548 check_added_monitors!(nodes[0], 1);
5549 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5551 expect_payment_failed!(nodes[0], our_payment_hash, true);
5555 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5556 // There are only a few cases to test here:
5557 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5558 // broadcastable commitment transactions result in channel closure,
5559 // * its included in an unrevoked-but-previous remote commitment transaction,
5560 // * its included in the latest remote or local commitment transactions.
5561 // We test each of the three possible commitment transactions individually and use both dust and
5563 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5564 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5565 // tested for at least one of the cases in other tests.
5567 fn htlc_claim_single_commitment_only_a() {
5568 do_htlc_claim_local_commitment_only(true);
5569 do_htlc_claim_local_commitment_only(false);
5571 do_htlc_claim_current_remote_commitment_only(true);
5572 do_htlc_claim_current_remote_commitment_only(false);
5576 fn htlc_claim_single_commitment_only_b() {
5577 do_htlc_claim_previous_remote_commitment_only(true, false);
5578 do_htlc_claim_previous_remote_commitment_only(false, false);
5579 do_htlc_claim_previous_remote_commitment_only(true, true);
5580 do_htlc_claim_previous_remote_commitment_only(false, true);
5585 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5586 let chanmon_cfgs = create_chanmon_cfgs(2);
5587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5589 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5590 // Force duplicate randomness for every get-random call
5591 for node in nodes.iter() {
5592 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5595 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5596 let channel_value_satoshis=10000;
5597 let push_msat=10001;
5598 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5599 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5600 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5601 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5603 // Create a second channel with the same random values. This used to panic due to a colliding
5604 // channel_id, but now panics due to a colliding outbound SCID alias.
5605 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5609 fn bolt2_open_channel_sending_node_checks_part2() {
5610 let chanmon_cfgs = create_chanmon_cfgs(2);
5611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5613 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5615 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5616 let channel_value_satoshis=2^24;
5617 let push_msat=10001;
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 push_msat to equal or less than 1000 * funding_satoshis
5621 let channel_value_satoshis=10000;
5622 // Test when push_msat is equal to 1000 * funding_satoshis.
5623 let push_msat=1000*channel_value_satoshis+1;
5624 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5626 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5627 let channel_value_satoshis=10000;
5628 let push_msat=10001;
5629 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
5630 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5631 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5633 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5634 // 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
5635 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5637 // 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.
5638 assert!(BREAKDOWN_TIMEOUT>0);
5639 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5641 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5642 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5643 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5645 // 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.
5646 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5647 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5648 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5649 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5650 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5654 fn bolt2_open_channel_sane_dust_limit() {
5655 let chanmon_cfgs = create_chanmon_cfgs(2);
5656 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5657 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5658 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5660 let channel_value_satoshis=1000000;
5661 let push_msat=10001;
5662 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5663 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5664 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5665 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5667 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5668 let events = nodes[1].node.get_and_clear_pending_msg_events();
5669 let err_msg = match events[0] {
5670 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5673 _ => panic!("Unexpected event"),
5675 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5678 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5679 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5680 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5681 // is no longer affordable once it's freed.
5683 fn test_fail_holding_cell_htlc_upon_free() {
5684 let chanmon_cfgs = create_chanmon_cfgs(2);
5685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5687 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5688 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5690 // First nodes[0] generates an update_fee, setting the channel's
5691 // pending_update_fee.
5693 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5694 *feerate_lock += 20;
5696 nodes[0].node.timer_tick_occurred();
5697 check_added_monitors!(nodes[0], 1);
5699 let events = nodes[0].node.get_and_clear_pending_msg_events();
5700 assert_eq!(events.len(), 1);
5701 let (update_msg, commitment_signed) = match events[0] {
5702 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5703 (update_fee.as_ref(), commitment_signed)
5705 _ => panic!("Unexpected event"),
5708 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5710 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5711 let channel_reserve = chan_stat.channel_reserve_msat;
5712 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5713 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5715 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5716 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5717 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5719 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5720 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5721 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5722 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5723 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5725 // Flush the pending fee update.
5726 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5727 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5728 check_added_monitors!(nodes[1], 1);
5729 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5730 check_added_monitors!(nodes[0], 1);
5732 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5733 // HTLC, but now that the fee has been raised the payment will now fail, causing
5734 // us to surface its failure to the user.
5735 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5736 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5737 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);
5739 // Check that the payment failed to be sent out.
5740 let events = nodes[0].node.get_and_clear_pending_events();
5741 assert_eq!(events.len(), 2);
5743 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5744 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5745 assert_eq!(our_payment_hash.clone(), *payment_hash);
5746 assert_eq!(*payment_failed_permanently, false);
5747 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5749 _ => panic!("Unexpected event"),
5752 &Event::PaymentFailed { ref payment_hash, .. } => {
5753 assert_eq!(our_payment_hash.clone(), *payment_hash);
5755 _ => panic!("Unexpected event"),
5759 // Test that if multiple HTLCs are released from the holding cell and one is
5760 // valid but the other is no longer valid upon release, the valid HTLC can be
5761 // successfully completed while the other one fails as expected.
5763 fn test_free_and_fail_holding_cell_htlcs() {
5764 let chanmon_cfgs = create_chanmon_cfgs(2);
5765 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5766 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5767 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5768 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5770 // First nodes[0] generates an update_fee, setting the channel's
5771 // pending_update_fee.
5773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5774 *feerate_lock += 200;
5776 nodes[0].node.timer_tick_occurred();
5777 check_added_monitors!(nodes[0], 1);
5779 let events = nodes[0].node.get_and_clear_pending_msg_events();
5780 assert_eq!(events.len(), 1);
5781 let (update_msg, commitment_signed) = match events[0] {
5782 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5783 (update_fee.as_ref(), commitment_signed)
5785 _ => panic!("Unexpected event"),
5788 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5790 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5791 let channel_reserve = chan_stat.channel_reserve_msat;
5792 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5793 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5795 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5797 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5798 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5799 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5801 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5802 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5803 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5804 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5805 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5806 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5807 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5808 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5809 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5810 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5812 // Flush the pending fee update.
5813 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5814 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5815 check_added_monitors!(nodes[1], 1);
5816 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5817 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5818 check_added_monitors!(nodes[0], 2);
5820 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5821 // but now that the fee has been raised the second payment will now fail, causing us
5822 // to surface its failure to the user. The first payment should succeed.
5823 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5824 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5825 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);
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].hops[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 // Avoid having to include routing fees in calculations
5892 let mut config = test_default_channel_config();
5893 config.channel_config.forwarding_fee_base_msat = 0;
5894 config.channel_config.forwarding_fee_proportional_millionths = 0;
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.
5926 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5927 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5928 let payment_event = {
5929 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5930 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5931 check_added_monitors!(nodes[0], 1);
5933 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5934 assert_eq!(events.len(), 1);
5936 SendEvent::from_event(events.remove(0))
5938 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5939 check_added_monitors!(nodes[1], 0);
5940 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5941 expect_pending_htlcs_forwardable!(nodes[1]);
5943 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5944 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5946 // Flush the pending fee update.
5947 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5948 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5949 check_added_monitors!(nodes[2], 1);
5950 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5951 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5952 check_added_monitors!(nodes[1], 2);
5954 // A final RAA message is generated to finalize the fee update.
5955 let events = nodes[1].node.get_and_clear_pending_msg_events();
5956 assert_eq!(events.len(), 1);
5958 let raa_msg = match &events[0] {
5959 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5962 _ => panic!("Unexpected event"),
5965 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5966 check_added_monitors!(nodes[2], 1);
5967 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5969 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5970 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5971 assert_eq!(process_htlc_forwards_event.len(), 2);
5972 match &process_htlc_forwards_event[0] {
5973 &Event::PendingHTLCsForwardable { .. } => {},
5974 _ => panic!("Unexpected event"),
5977 // In response, we call ChannelManager's process_pending_htlc_forwards
5978 nodes[1].node.process_pending_htlc_forwards();
5979 check_added_monitors!(nodes[1], 1);
5981 // This causes the HTLC to be failed backwards.
5982 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5983 assert_eq!(fail_event.len(), 1);
5984 let (fail_msg, commitment_signed) = match &fail_event[0] {
5985 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5986 assert_eq!(updates.update_add_htlcs.len(), 0);
5987 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5988 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5989 assert_eq!(updates.update_fail_htlcs.len(), 1);
5990 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5992 _ => panic!("Unexpected event"),
5995 // Pass the failure messages back to nodes[0].
5996 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5997 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5999 // Complete the HTLC failure+removal process.
6000 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6001 check_added_monitors!(nodes[0], 1);
6002 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6003 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6004 check_added_monitors!(nodes[1], 2);
6005 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6006 assert_eq!(final_raa_event.len(), 1);
6007 let raa = match &final_raa_event[0] {
6008 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6009 _ => panic!("Unexpected event"),
6011 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6012 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6013 check_added_monitors!(nodes[0], 1);
6016 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6017 // 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.
6018 //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.
6021 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6022 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6023 let chanmon_cfgs = create_chanmon_cfgs(2);
6024 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6025 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6026 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6027 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6029 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6030 route.paths[0].hops[0].fee_msat = 100;
6032 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6033 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6034 ), true, APIError::ChannelUnavailable { .. }, {});
6035 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6039 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6040 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6041 let chanmon_cfgs = create_chanmon_cfgs(2);
6042 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6043 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6044 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6045 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6047 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6048 route.paths[0].hops[0].fee_msat = 0;
6049 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6050 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6051 true, APIError::ChannelUnavailable { ref err },
6052 assert_eq!(err, "Cannot send 0-msat HTLC"));
6054 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6055 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6059 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6060 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6061 let chanmon_cfgs = create_chanmon_cfgs(2);
6062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6064 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6065 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6067 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6068 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6069 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6070 check_added_monitors!(nodes[0], 1);
6071 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6072 updates.update_add_htlcs[0].amount_msat = 0;
6074 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6075 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6076 check_closed_broadcast!(nodes[1], true).unwrap();
6077 check_added_monitors!(nodes[1], 1);
6078 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6082 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6083 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6084 //It is enforced when constructing a route.
6085 let chanmon_cfgs = create_chanmon_cfgs(2);
6086 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6087 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6088 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6089 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6091 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6092 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6093 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6094 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6095 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6096 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6097 ), true, APIError::InvalidRoute { ref err },
6098 assert_eq!(err, &"Channel CLTV overflowed?"));
6102 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6103 //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.
6104 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6105 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6106 let chanmon_cfgs = create_chanmon_cfgs(2);
6107 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6108 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6109 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6110 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6111 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6112 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context.counterparty_max_accepted_htlcs as u64;
6114 // Fetch a route in advance as we will be unable to once we're unable to send.
6115 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6116 for i in 0..max_accepted_htlcs {
6117 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6118 let payment_event = {
6119 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6120 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6121 check_added_monitors!(nodes[0], 1);
6123 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6124 assert_eq!(events.len(), 1);
6125 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6126 assert_eq!(htlcs[0].htlc_id, i);
6130 SendEvent::from_event(events.remove(0))
6132 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6133 check_added_monitors!(nodes[1], 0);
6134 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6136 expect_pending_htlcs_forwardable!(nodes[1]);
6137 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6139 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6140 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6141 ), true, APIError::ChannelUnavailable { .. }, {});
6143 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6147 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6148 //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.
6149 let chanmon_cfgs = create_chanmon_cfgs(2);
6150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6152 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6153 let channel_value = 100000;
6154 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6155 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6157 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6159 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6160 // Manually create a route over our max in flight (which our router normally automatically
6162 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6163 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6164 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6165 ), true, APIError::ChannelUnavailable { .. }, {});
6166 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6168 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6171 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6173 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6174 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6175 let chanmon_cfgs = create_chanmon_cfgs(2);
6176 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6177 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6178 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6179 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6180 let htlc_minimum_msat: u64;
6182 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6183 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6184 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6185 htlc_minimum_msat = channel.context.get_holder_htlc_minimum_msat();
6188 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6189 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6190 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6191 check_added_monitors!(nodes[0], 1);
6192 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6193 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6194 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6195 assert!(nodes[1].node.list_channels().is_empty());
6196 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6197 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()));
6198 check_added_monitors!(nodes[1], 1);
6199 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6203 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6204 //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
6205 let chanmon_cfgs = create_chanmon_cfgs(2);
6206 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6207 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6208 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6209 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6211 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6212 let channel_reserve = chan_stat.channel_reserve_msat;
6213 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6214 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6215 // The 2* and +1 are for the fee spike reserve.
6216 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6218 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6219 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6220 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6221 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6222 check_added_monitors!(nodes[0], 1);
6223 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6225 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6226 // at this time channel-initiatee receivers are not required to enforce that senders
6227 // respect the fee_spike_reserve.
6228 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6231 assert!(nodes[1].node.list_channels().is_empty());
6232 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6233 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6234 check_added_monitors!(nodes[1], 1);
6235 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6239 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6240 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6241 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6242 let chanmon_cfgs = create_chanmon_cfgs(2);
6243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6245 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6246 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6248 let send_amt = 3999999;
6249 let (mut route, our_payment_hash, _, our_payment_secret) =
6250 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6251 route.paths[0].hops[0].fee_msat = send_amt;
6252 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6253 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6254 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6255 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6256 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6257 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6259 let mut msg = msgs::UpdateAddHTLC {
6263 payment_hash: our_payment_hash,
6264 cltv_expiry: htlc_cltv,
6265 onion_routing_packet: onion_packet.clone(),
6266 skimmed_fee_msat: None,
6270 msg.htlc_id = i as u64;
6271 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6273 msg.htlc_id = (50) as u64;
6274 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6276 assert!(nodes[1].node.list_channels().is_empty());
6277 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6278 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6279 check_added_monitors!(nodes[1], 1);
6280 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6284 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6285 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6286 let chanmon_cfgs = create_chanmon_cfgs(2);
6287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6289 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6290 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6292 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6293 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6294 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6295 check_added_monitors!(nodes[0], 1);
6296 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6297 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;
6298 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6300 assert!(nodes[1].node.list_channels().is_empty());
6301 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6302 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6303 check_added_monitors!(nodes[1], 1);
6304 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6308 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6309 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6310 let chanmon_cfgs = create_chanmon_cfgs(2);
6311 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6312 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6313 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6315 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6316 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6317 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6318 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6319 check_added_monitors!(nodes[0], 1);
6320 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6321 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6324 assert!(nodes[1].node.list_channels().is_empty());
6325 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6326 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6327 check_added_monitors!(nodes[1], 1);
6328 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6332 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6333 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6334 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6335 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6336 let chanmon_cfgs = create_chanmon_cfgs(2);
6337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6339 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6341 create_announced_chan_between_nodes(&nodes, 0, 1);
6342 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6343 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6344 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6345 check_added_monitors!(nodes[0], 1);
6346 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6347 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6349 //Disconnect and Reconnect
6350 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6351 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6352 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6353 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6355 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6356 assert_eq!(reestablish_1.len(), 1);
6357 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6358 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
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().context.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().context.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); // 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, 11);
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 OutboundV1Channel::new()
6965 if let Err(error) = OutboundV1Channel::new(&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 InboundV1Channel::new()
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) = InboundV1Channel::new(&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 InboundV1Channel::new()
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) = InboundV1Channel::new(&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_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7039 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None, 10_000, 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 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7104 nodes[0].node.timer_tick_occurred();
7106 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7107 assert_eq!(msg_events.len(), 3);
7108 let mut chans_disabled = HashMap::new();
7109 for e in msg_events {
7111 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7112 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7113 // Check that each channel gets updated exactly once
7114 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7115 panic!("Generated ChannelUpdate for wrong chan!");
7118 _ => panic!("Unexpected event"),
7122 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7123 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7125 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7126 assert_eq!(reestablish_1.len(), 3);
7127 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7128 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7130 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7131 assert_eq!(reestablish_2.len(), 3);
7133 // Reestablish chan_1
7134 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
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[0]);
7137 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7138 // Reestablish chan_2
7139 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
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[1]);
7142 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7143 // Reestablish chan_3
7144 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7145 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7146 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7147 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7149 for _ in 0..ENABLE_GOSSIP_TICKS {
7150 nodes[0].node.timer_tick_occurred();
7152 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7153 nodes[0].node.timer_tick_occurred();
7154 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7155 assert_eq!(msg_events.len(), 3);
7156 for e in msg_events {
7158 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7159 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7160 match chans_disabled.remove(&msg.contents.short_channel_id) {
7161 // Each update should have a higher timestamp than the previous one, replacing
7163 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7164 None => panic!("Generated ChannelUpdate for wrong chan!"),
7167 _ => panic!("Unexpected event"),
7170 // Check that each channel gets updated exactly once
7171 assert!(chans_disabled.is_empty());
7175 fn test_bump_penalty_txn_on_revoked_commitment() {
7176 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7177 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7179 let chanmon_cfgs = create_chanmon_cfgs(2);
7180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7182 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7184 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7186 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7187 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7188 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7189 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7190 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7192 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7193 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7194 assert_eq!(revoked_txn[0].output.len(), 4);
7195 assert_eq!(revoked_txn[0].input.len(), 1);
7196 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7197 let revoked_txid = revoked_txn[0].txid();
7199 let mut penalty_sum = 0;
7200 for outp in revoked_txn[0].output.iter() {
7201 if outp.script_pubkey.is_v0_p2wsh() {
7202 penalty_sum += outp.value;
7206 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7207 let header_114 = connect_blocks(&nodes[1], 14);
7209 // Actually revoke tx by claiming a HTLC
7210 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7211 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7212 check_added_monitors!(nodes[1], 1);
7214 // One or more justice tx should have been broadcast, check it
7218 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7219 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7220 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7221 assert_eq!(node_txn[0].output.len(), 1);
7222 check_spends!(node_txn[0], revoked_txn[0]);
7223 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7224 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7225 penalty_1 = node_txn[0].txid();
7229 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7230 connect_blocks(&nodes[1], 15);
7231 let mut penalty_2 = penalty_1;
7232 let mut feerate_2 = 0;
7234 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7235 assert_eq!(node_txn.len(), 1);
7236 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7237 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7238 assert_eq!(node_txn[0].output.len(), 1);
7239 check_spends!(node_txn[0], revoked_txn[0]);
7240 penalty_2 = node_txn[0].txid();
7241 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7242 assert_ne!(penalty_2, penalty_1);
7243 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7244 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7245 // Verify 25% bump heuristic
7246 assert!(feerate_2 * 100 >= feerate_1 * 125);
7250 assert_ne!(feerate_2, 0);
7252 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7253 connect_blocks(&nodes[1], 1);
7255 let mut feerate_3 = 0;
7257 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7258 assert_eq!(node_txn.len(), 1);
7259 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7260 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7261 assert_eq!(node_txn[0].output.len(), 1);
7262 check_spends!(node_txn[0], revoked_txn[0]);
7263 penalty_3 = node_txn[0].txid();
7264 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7265 assert_ne!(penalty_3, penalty_2);
7266 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7267 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7268 // Verify 25% bump heuristic
7269 assert!(feerate_3 * 100 >= feerate_2 * 125);
7273 assert_ne!(feerate_3, 0);
7275 nodes[1].node.get_and_clear_pending_events();
7276 nodes[1].node.get_and_clear_pending_msg_events();
7280 fn test_bump_penalty_txn_on_revoked_htlcs() {
7281 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7282 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7284 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7285 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7286 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7287 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7288 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7290 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7291 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7292 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7293 let scorer = test_utils::TestScorer::new();
7294 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7295 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7296 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7297 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7298 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7299 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7300 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7301 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7303 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7304 assert_eq!(revoked_local_txn[0].input.len(), 1);
7305 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7307 // Revoke local commitment tx
7308 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7310 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7311 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7312 check_closed_broadcast!(nodes[1], true);
7313 check_added_monitors!(nodes[1], 1);
7314 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7315 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7317 let revoked_htlc_txn = {
7318 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7319 assert_eq!(txn.len(), 2);
7321 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7322 assert_eq!(txn[0].input.len(), 1);
7323 check_spends!(txn[0], revoked_local_txn[0]);
7325 assert_eq!(txn[1].input.len(), 1);
7326 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7327 assert_eq!(txn[1].output.len(), 1);
7328 check_spends!(txn[1], revoked_local_txn[0]);
7333 // Broadcast set of revoked txn on A
7334 let hash_128 = connect_blocks(&nodes[0], 40);
7335 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7336 connect_block(&nodes[0], &block_11);
7337 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7338 connect_block(&nodes[0], &block_129);
7339 let events = nodes[0].node.get_and_clear_pending_events();
7340 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7341 match events.last().unwrap() {
7342 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7343 _ => panic!("Unexpected event"),
7349 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7350 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7351 // Verify claim tx are spending revoked HTLC txn
7353 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7354 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7355 // which are included in the same block (they are broadcasted because we scan the
7356 // transactions linearly and generate claims as we go, they likely should be removed in the
7358 assert_eq!(node_txn[0].input.len(), 1);
7359 check_spends!(node_txn[0], revoked_local_txn[0]);
7360 assert_eq!(node_txn[1].input.len(), 1);
7361 check_spends!(node_txn[1], revoked_local_txn[0]);
7362 assert_eq!(node_txn[2].input.len(), 1);
7363 check_spends!(node_txn[2], revoked_local_txn[0]);
7365 // Each of the three justice transactions claim a separate (single) output of the three
7366 // available, which we check here:
7367 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7368 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7369 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7371 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7372 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7374 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7375 // output, checked above).
7376 assert_eq!(node_txn[3].input.len(), 2);
7377 assert_eq!(node_txn[3].output.len(), 1);
7378 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7380 first = node_txn[3].txid();
7381 // Store both feerates for later comparison
7382 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7383 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7384 penalty_txn = vec![node_txn[2].clone()];
7388 // Connect one more block to see if bumped penalty are issued for HTLC txn
7389 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7390 connect_block(&nodes[0], &block_130);
7391 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7392 connect_block(&nodes[0], &block_131);
7394 // Few more blocks to confirm penalty txn
7395 connect_blocks(&nodes[0], 4);
7396 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7397 let header_144 = connect_blocks(&nodes[0], 9);
7399 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7400 assert_eq!(node_txn.len(), 1);
7402 assert_eq!(node_txn[0].input.len(), 2);
7403 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7404 // Verify bumped tx is different and 25% bump heuristic
7405 assert_ne!(first, node_txn[0].txid());
7406 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7407 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7408 assert!(feerate_2 * 100 > feerate_1 * 125);
7409 let txn = vec![node_txn[0].clone()];
7413 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7414 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7415 connect_blocks(&nodes[0], 20);
7417 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7418 // We verify than no new transaction has been broadcast because previously
7419 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7420 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7421 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7422 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7423 // up bumped justice generation.
7424 assert_eq!(node_txn.len(), 0);
7427 check_closed_broadcast!(nodes[0], true);
7428 check_added_monitors!(nodes[0], 1);
7432 fn test_bump_penalty_txn_on_remote_commitment() {
7433 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7434 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7437 // Provide preimage for one
7438 // Check aggregation
7440 let chanmon_cfgs = create_chanmon_cfgs(2);
7441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7443 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7445 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7446 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7447 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7449 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7450 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7451 assert_eq!(remote_txn[0].output.len(), 4);
7452 assert_eq!(remote_txn[0].input.len(), 1);
7453 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7455 // Claim a HTLC without revocation (provide B monitor with preimage)
7456 nodes[1].node.claim_funds(payment_preimage);
7457 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7458 mine_transaction(&nodes[1], &remote_txn[0]);
7459 check_added_monitors!(nodes[1], 2);
7460 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7462 // One or more claim tx should have been broadcast, check it
7466 let feerate_timeout;
7467 let feerate_preimage;
7469 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7470 // 3 transactions including:
7471 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7472 assert_eq!(node_txn.len(), 3);
7473 assert_eq!(node_txn[0].input.len(), 1);
7474 assert_eq!(node_txn[1].input.len(), 1);
7475 assert_eq!(node_txn[2].input.len(), 1);
7476 check_spends!(node_txn[0], remote_txn[0]);
7477 check_spends!(node_txn[1], remote_txn[0]);
7478 check_spends!(node_txn[2], remote_txn[0]);
7480 preimage = node_txn[0].txid();
7481 let index = node_txn[0].input[0].previous_output.vout;
7482 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7483 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7485 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7486 (node_txn[2].clone(), node_txn[1].clone())
7488 (node_txn[1].clone(), node_txn[2].clone())
7491 preimage_bump = preimage_bump_tx;
7492 check_spends!(preimage_bump, remote_txn[0]);
7493 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7495 timeout = timeout_tx.txid();
7496 let index = timeout_tx.input[0].previous_output.vout;
7497 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7498 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7502 assert_ne!(feerate_timeout, 0);
7503 assert_ne!(feerate_preimage, 0);
7505 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7506 connect_blocks(&nodes[1], 1);
7508 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7509 assert_eq!(node_txn.len(), 1);
7510 assert_eq!(node_txn[0].input.len(), 1);
7511 assert_eq!(preimage_bump.input.len(), 1);
7512 check_spends!(node_txn[0], remote_txn[0]);
7513 check_spends!(preimage_bump, remote_txn[0]);
7515 let index = preimage_bump.input[0].previous_output.vout;
7516 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7517 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7518 assert!(new_feerate * 100 > feerate_timeout * 125);
7519 assert_ne!(timeout, preimage_bump.txid());
7521 let index = node_txn[0].input[0].previous_output.vout;
7522 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7523 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7524 assert!(new_feerate * 100 > feerate_preimage * 125);
7525 assert_ne!(preimage, node_txn[0].txid());
7530 nodes[1].node.get_and_clear_pending_events();
7531 nodes[1].node.get_and_clear_pending_msg_events();
7535 fn test_counterparty_raa_skip_no_crash() {
7536 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7537 // commitment transaction, we would have happily carried on and provided them the next
7538 // commitment transaction based on one RAA forward. This would probably eventually have led to
7539 // channel closure, but it would not have resulted in funds loss. Still, our
7540 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7541 // check simply that the channel is closed in response to such an RAA, but don't check whether
7542 // we decide to punish our counterparty for revoking their funds (as we don't currently
7544 let chanmon_cfgs = create_chanmon_cfgs(2);
7545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7547 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7548 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7550 let per_commitment_secret;
7551 let next_per_commitment_point;
7553 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7554 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7555 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7557 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7559 // Make signer believe we got a counterparty signature, so that it allows the revocation
7560 keys.get_enforcement_state().last_holder_commitment -= 1;
7561 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7563 // Must revoke without gaps
7564 keys.get_enforcement_state().last_holder_commitment -= 1;
7565 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7567 keys.get_enforcement_state().last_holder_commitment -= 1;
7568 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7569 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7572 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7573 &msgs::RevokeAndACK {
7575 per_commitment_secret,
7576 next_per_commitment_point,
7578 next_local_nonce: None,
7580 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7581 check_added_monitors!(nodes[1], 1);
7582 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7586 fn test_bump_txn_sanitize_tracking_maps() {
7587 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7588 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7590 let chanmon_cfgs = create_chanmon_cfgs(2);
7591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7593 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7595 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7596 // Lock HTLC in both directions
7597 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7598 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7600 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7601 assert_eq!(revoked_local_txn[0].input.len(), 1);
7602 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7604 // Revoke local commitment tx
7605 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7607 // Broadcast set of revoked txn on A
7608 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7609 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7610 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7612 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7613 check_closed_broadcast!(nodes[0], true);
7614 check_added_monitors!(nodes[0], 1);
7615 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7617 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7618 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7619 check_spends!(node_txn[0], revoked_local_txn[0]);
7620 check_spends!(node_txn[1], revoked_local_txn[0]);
7621 check_spends!(node_txn[2], revoked_local_txn[0]);
7622 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7626 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7627 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7629 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7630 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7631 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7636 fn test_channel_conf_timeout() {
7637 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7638 // confirm within 2016 blocks, as recommended by BOLT 2.
7639 let chanmon_cfgs = create_chanmon_cfgs(2);
7640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7644 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7646 // The outbound node should wait forever for confirmation:
7647 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7648 // copied here instead of directly referencing the constant.
7649 connect_blocks(&nodes[0], 2016);
7650 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7652 // The inbound node should fail the channel after exactly 2016 blocks
7653 connect_blocks(&nodes[1], 2015);
7654 check_added_monitors!(nodes[1], 0);
7655 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7657 connect_blocks(&nodes[1], 1);
7658 check_added_monitors!(nodes[1], 1);
7659 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7660 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7661 assert_eq!(close_ev.len(), 1);
7663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7664 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7665 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7667 _ => panic!("Unexpected event"),
7672 fn test_override_channel_config() {
7673 let chanmon_cfgs = create_chanmon_cfgs(2);
7674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7676 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7678 // Node0 initiates a channel to node1 using the override config.
7679 let mut override_config = UserConfig::default();
7680 override_config.channel_handshake_config.our_to_self_delay = 200;
7682 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7684 // Assert the channel created by node0 is using the override config.
7685 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7686 assert_eq!(res.channel_flags, 0);
7687 assert_eq!(res.to_self_delay, 200);
7691 fn test_override_0msat_htlc_minimum() {
7692 let mut zero_config = UserConfig::default();
7693 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7694 let chanmon_cfgs = create_chanmon_cfgs(2);
7695 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7696 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7697 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7699 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7700 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7701 assert_eq!(res.htlc_minimum_msat, 1);
7703 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7704 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7705 assert_eq!(res.htlc_minimum_msat, 1);
7709 fn test_channel_update_has_correct_htlc_maximum_msat() {
7710 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7711 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7712 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7713 // 90% of the `channel_value`.
7714 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7716 let mut config_30_percent = UserConfig::default();
7717 config_30_percent.channel_handshake_config.announced_channel = true;
7718 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7719 let mut config_50_percent = UserConfig::default();
7720 config_50_percent.channel_handshake_config.announced_channel = true;
7721 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7722 let mut config_95_percent = UserConfig::default();
7723 config_95_percent.channel_handshake_config.announced_channel = true;
7724 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7725 let mut config_100_percent = UserConfig::default();
7726 config_100_percent.channel_handshake_config.announced_channel = true;
7727 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7729 let chanmon_cfgs = create_chanmon_cfgs(4);
7730 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7731 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)]);
7732 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7734 let channel_value_satoshis = 100000;
7735 let channel_value_msat = channel_value_satoshis * 1000;
7736 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7737 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7738 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7740 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7741 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7743 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7744 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7745 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7746 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7747 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7748 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7750 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7751 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7753 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7754 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7755 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7757 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7761 fn test_manually_accept_inbound_channel_request() {
7762 let mut manually_accept_conf = UserConfig::default();
7763 manually_accept_conf.manually_accept_inbound_channels = true;
7764 let chanmon_cfgs = create_chanmon_cfgs(2);
7765 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7766 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7767 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7769 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7770 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7772 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7774 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7775 // accepting the inbound channel request.
7776 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7778 let events = nodes[1].node.get_and_clear_pending_events();
7780 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7781 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7783 _ => panic!("Unexpected event"),
7786 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7787 assert_eq!(accept_msg_ev.len(), 1);
7789 match accept_msg_ev[0] {
7790 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7791 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7793 _ => panic!("Unexpected event"),
7796 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7798 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7799 assert_eq!(close_msg_ev.len(), 1);
7801 let events = nodes[1].node.get_and_clear_pending_events();
7803 Event::ChannelClosed { user_channel_id, .. } => {
7804 assert_eq!(user_channel_id, 23);
7806 _ => panic!("Unexpected event"),
7811 fn test_manually_reject_inbound_channel_request() {
7812 let mut manually_accept_conf = UserConfig::default();
7813 manually_accept_conf.manually_accept_inbound_channels = true;
7814 let chanmon_cfgs = create_chanmon_cfgs(2);
7815 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7816 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7817 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7819 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7820 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7822 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7824 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7825 // rejecting the inbound channel request.
7826 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7828 let events = nodes[1].node.get_and_clear_pending_events();
7830 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7831 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7833 _ => panic!("Unexpected event"),
7836 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7837 assert_eq!(close_msg_ev.len(), 1);
7839 match close_msg_ev[0] {
7840 MessageSendEvent::HandleError { ref node_id, .. } => {
7841 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7843 _ => panic!("Unexpected event"),
7845 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7849 fn test_reject_funding_before_inbound_channel_accepted() {
7850 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7851 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7852 // the node operator before the counterparty sends a `FundingCreated` message. If a
7853 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7854 // and the channel should be closed.
7855 let mut manually_accept_conf = UserConfig::default();
7856 manually_accept_conf.manually_accept_inbound_channels = true;
7857 let chanmon_cfgs = create_chanmon_cfgs(2);
7858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7862 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7863 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7864 let temp_channel_id = res.temporary_channel_id;
7866 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7868 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7869 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7871 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7872 nodes[1].node.get_and_clear_pending_events();
7874 // Get the `AcceptChannel` message of `nodes[1]` without calling
7875 // `ChannelManager::accept_inbound_channel`, which generates a
7876 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7877 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7878 // succeed when `nodes[0]` is passed to it.
7879 let accept_chan_msg = {
7880 let mut node_1_per_peer_lock;
7881 let mut node_1_peer_state_lock;
7882 let channel = get_inbound_v1_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7883 channel.get_accept_channel_message()
7885 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7887 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7889 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7890 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7892 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7893 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7895 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7896 assert_eq!(close_msg_ev.len(), 1);
7898 let expected_err = "FundingCreated message received before the channel was accepted";
7899 match close_msg_ev[0] {
7900 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7901 assert_eq!(msg.channel_id, temp_channel_id);
7902 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7903 assert_eq!(msg.data, expected_err);
7905 _ => panic!("Unexpected event"),
7908 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7912 fn test_can_not_accept_inbound_channel_twice() {
7913 let mut manually_accept_conf = UserConfig::default();
7914 manually_accept_conf.manually_accept_inbound_channels = true;
7915 let chanmon_cfgs = create_chanmon_cfgs(2);
7916 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7917 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7918 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7920 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7921 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7923 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7925 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7926 // accepting the inbound channel request.
7927 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7929 let events = nodes[1].node.get_and_clear_pending_events();
7931 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7932 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7933 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7935 Err(APIError::APIMisuseError { err }) => {
7936 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7938 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7939 Err(_) => panic!("Unexpected Error"),
7942 _ => panic!("Unexpected event"),
7945 // Ensure that the channel wasn't closed after attempting to accept it twice.
7946 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7947 assert_eq!(accept_msg_ev.len(), 1);
7949 match accept_msg_ev[0] {
7950 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7951 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7953 _ => panic!("Unexpected event"),
7958 fn test_can_not_accept_unknown_inbound_channel() {
7959 let chanmon_cfg = create_chanmon_cfgs(2);
7960 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7961 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7962 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7964 let unknown_channel_id = [0; 32];
7965 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7967 Err(APIError::ChannelUnavailable { err }) => {
7968 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()));
7970 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7971 Err(_) => panic!("Unexpected Error"),
7976 fn test_onion_value_mpp_set_calculation() {
7977 // Test that we use the onion value `amt_to_forward` when
7978 // calculating whether we've reached the `total_msat` of an MPP
7979 // by having a routing node forward more than `amt_to_forward`
7980 // and checking that the receiving node doesn't generate
7981 // a PaymentClaimable event too early
7983 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7984 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7985 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7986 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7988 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7989 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7990 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7991 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7993 let total_msat = 100_000;
7994 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7995 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7996 let sample_path = route.paths.pop().unwrap();
7998 let mut path_1 = sample_path.clone();
7999 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8000 path_1.hops[0].short_channel_id = chan_1_id;
8001 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8002 path_1.hops[1].short_channel_id = chan_3_id;
8003 path_1.hops[1].fee_msat = 100_000;
8004 route.paths.push(path_1);
8006 let mut path_2 = sample_path.clone();
8007 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8008 path_2.hops[0].short_channel_id = chan_2_id;
8009 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8010 path_2.hops[1].short_channel_id = chan_4_id;
8011 path_2.hops[1].fee_msat = 1_000;
8012 route.paths.push(path_2);
8015 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8016 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8017 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8018 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8019 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8020 check_added_monitors!(nodes[0], expected_paths.len());
8022 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8023 assert_eq!(events.len(), expected_paths.len());
8026 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8027 let mut payment_event = SendEvent::from_event(ev);
8028 let mut prev_node = &nodes[0];
8030 for (idx, &node) in expected_paths[0].iter().enumerate() {
8031 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8033 if idx == 0 { // routing node
8034 let session_priv = [3; 32];
8035 let height = nodes[0].best_block_info().1;
8036 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8037 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8038 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8039 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8040 // Edit amt_to_forward to simulate the sender having set
8041 // the final amount and the routing node taking less fee
8042 onion_payloads[1].amt_to_forward = 99_000;
8043 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8044 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8047 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8048 check_added_monitors!(node, 0);
8049 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8050 expect_pending_htlcs_forwardable!(node);
8053 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8054 assert_eq!(events_2.len(), 1);
8055 check_added_monitors!(node, 1);
8056 payment_event = SendEvent::from_event(events_2.remove(0));
8057 assert_eq!(payment_event.msgs.len(), 1);
8059 let events_2 = node.node.get_and_clear_pending_events();
8060 assert!(events_2.is_empty());
8067 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8068 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8070 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8073 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8075 let routing_node_count = msat_amounts.len();
8076 let node_count = routing_node_count + 2;
8078 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8079 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8080 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8081 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8086 // Create channels for each amount
8087 let mut expected_paths = Vec::with_capacity(routing_node_count);
8088 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8089 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8090 for i in 0..routing_node_count {
8091 let routing_node = 2 + i;
8092 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8093 src_chan_ids.push(src_chan_id);
8094 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8095 dst_chan_ids.push(dst_chan_id);
8096 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8097 expected_paths.push(path);
8099 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8101 // Create a route for each amount
8102 let example_amount = 100000;
8103 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);
8104 let sample_path = route.paths.pop().unwrap();
8105 for i in 0..routing_node_count {
8106 let routing_node = 2 + i;
8107 let mut path = sample_path.clone();
8108 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8109 path.hops[0].short_channel_id = src_chan_ids[i];
8110 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8111 path.hops[1].short_channel_id = dst_chan_ids[i];
8112 path.hops[1].fee_msat = msat_amounts[i];
8113 route.paths.push(path);
8116 // Send payment with manually set total_msat
8117 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8118 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8119 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8120 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8121 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8122 check_added_monitors!(nodes[src_idx], expected_paths.len());
8124 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8125 assert_eq!(events.len(), expected_paths.len());
8126 let mut amount_received = 0;
8127 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8128 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8130 let current_path_amount = msat_amounts[path_idx];
8131 amount_received += current_path_amount;
8132 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8133 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8136 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8140 fn test_overshoot_mpp() {
8141 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8142 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8146 fn test_simple_mpp() {
8147 // Simple test of sending a multi-path payment.
8148 let chanmon_cfgs = create_chanmon_cfgs(4);
8149 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8150 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8151 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8153 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8154 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8155 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8156 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8158 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8159 let path = route.paths[0].clone();
8160 route.paths.push(path);
8161 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8162 route.paths[0].hops[0].short_channel_id = chan_1_id;
8163 route.paths[0].hops[1].short_channel_id = chan_3_id;
8164 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8165 route.paths[1].hops[0].short_channel_id = chan_2_id;
8166 route.paths[1].hops[1].short_channel_id = chan_4_id;
8167 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8168 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8172 fn test_preimage_storage() {
8173 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8174 let chanmon_cfgs = create_chanmon_cfgs(2);
8175 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8176 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8177 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8179 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8182 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8183 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8184 nodes[0].node.send_payment_with_route(&route, payment_hash,
8185 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8186 check_added_monitors!(nodes[0], 1);
8187 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8188 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8189 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8190 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8192 // Note that after leaving the above scope we have no knowledge of any arguments or return
8193 // values from previous calls.
8194 expect_pending_htlcs_forwardable!(nodes[1]);
8195 let events = nodes[1].node.get_and_clear_pending_events();
8196 assert_eq!(events.len(), 1);
8198 Event::PaymentClaimable { ref purpose, .. } => {
8200 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8201 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8203 _ => panic!("expected PaymentPurpose::InvoicePayment")
8206 _ => panic!("Unexpected event"),
8211 fn test_bad_secret_hash() {
8212 // Simple test of unregistered payment hash/invalid payment secret handling
8213 let chanmon_cfgs = create_chanmon_cfgs(2);
8214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8216 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8218 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8220 let random_payment_hash = PaymentHash([42; 32]);
8221 let random_payment_secret = PaymentSecret([43; 32]);
8222 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8223 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8225 // All the below cases should end up being handled exactly identically, so we macro the
8226 // resulting events.
8227 macro_rules! handle_unknown_invalid_payment_data {
8228 ($payment_hash: expr) => {
8229 check_added_monitors!(nodes[0], 1);
8230 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8231 let payment_event = SendEvent::from_event(events.pop().unwrap());
8232 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8233 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8235 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8236 // again to process the pending backwards-failure of the HTLC
8237 expect_pending_htlcs_forwardable!(nodes[1]);
8238 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8239 check_added_monitors!(nodes[1], 1);
8241 // We should fail the payment back
8242 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8243 match events.pop().unwrap() {
8244 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8246 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8248 _ => panic!("Unexpected event"),
8253 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8254 // Error data is the HTLC value (100,000) and current block height
8255 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8257 // Send a payment with the right payment hash but the wrong payment secret
8258 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8259 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8260 handle_unknown_invalid_payment_data!(our_payment_hash);
8261 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8263 // Send a payment with a random payment hash, but the right payment secret
8264 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8265 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8266 handle_unknown_invalid_payment_data!(random_payment_hash);
8267 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8269 // Send a payment with a random payment hash and random payment secret
8270 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8271 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8272 handle_unknown_invalid_payment_data!(random_payment_hash);
8273 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8277 fn test_update_err_monitor_lockdown() {
8278 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8279 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8280 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8283 // This scenario may happen in a watchtower setup, where watchtower process a block height
8284 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8285 // commitment at same time.
8287 let chanmon_cfgs = create_chanmon_cfgs(2);
8288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8290 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8292 // Create some initial channel
8293 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8294 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8296 // Rebalance the network to generate htlc in the two directions
8297 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8299 // Route a HTLC from node 0 to node 1 (but don't settle)
8300 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8302 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8303 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8304 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8305 let persister = test_utils::TestPersister::new();
8308 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8309 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8310 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8311 assert!(new_monitor == *monitor);
8314 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);
8315 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8318 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8319 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8320 // transaction lock time requirements here.
8321 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8322 watchtower.chain_monitor.block_connected(&block, 200);
8324 // Try to update ChannelMonitor
8325 nodes[1].node.claim_funds(preimage);
8326 check_added_monitors!(nodes[1], 1);
8327 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8329 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8330 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8331 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8333 let mut node_0_per_peer_lock;
8334 let mut node_0_peer_state_lock;
8335 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8336 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8337 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8338 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8339 } else { assert!(false); }
8341 // Our local monitor is in-sync and hasn't processed yet timeout
8342 check_added_monitors!(nodes[0], 1);
8343 let events = nodes[0].node.get_and_clear_pending_events();
8344 assert_eq!(events.len(), 1);
8348 fn test_concurrent_monitor_claim() {
8349 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8350 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8351 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8352 // state N+1 confirms. Alice claims output from state N+1.
8354 let chanmon_cfgs = create_chanmon_cfgs(2);
8355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8357 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8359 // Create some initial channel
8360 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8361 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8363 // Rebalance the network to generate htlc in the two directions
8364 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8366 // Route a HTLC from node 0 to node 1 (but don't settle)
8367 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8369 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8370 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8371 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8372 let persister = test_utils::TestPersister::new();
8373 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8374 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8376 let watchtower_alice = {
8378 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8379 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8380 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8381 assert!(new_monitor == *monitor);
8384 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8385 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8388 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8389 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8390 // requirements here.
8391 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8392 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8393 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8395 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8397 let mut txn = alice_broadcaster.txn_broadcast();
8398 assert_eq!(txn.len(), 2);
8402 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8403 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8404 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8405 let persister = test_utils::TestPersister::new();
8406 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8407 let watchtower_bob = {
8409 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8410 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8411 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8412 assert!(new_monitor == *monitor);
8415 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8416 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8419 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8421 // Route another payment to generate another update with still previous HTLC pending
8422 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8423 nodes[1].node.send_payment_with_route(&route, payment_hash,
8424 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8425 check_added_monitors!(nodes[1], 1);
8427 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8428 assert_eq!(updates.update_add_htlcs.len(), 1);
8429 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8431 let mut node_0_per_peer_lock;
8432 let mut node_0_peer_state_lock;
8433 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8434 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8435 // Watchtower Alice should already have seen the block and reject the update
8436 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8437 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8438 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8439 } else { assert!(false); }
8441 // Our local monitor is in-sync and hasn't processed yet timeout
8442 check_added_monitors!(nodes[0], 1);
8444 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8445 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8447 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8450 let mut txn = bob_broadcaster.txn_broadcast();
8451 assert_eq!(txn.len(), 2);
8452 bob_state_y = txn.remove(0);
8455 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8456 let height = HTLC_TIMEOUT_BROADCAST + 1;
8457 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8458 check_closed_broadcast(&nodes[0], 1, true);
8459 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8460 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8461 check_added_monitors(&nodes[0], 1);
8463 let htlc_txn = alice_broadcaster.txn_broadcast();
8464 assert_eq!(htlc_txn.len(), 2);
8465 check_spends!(htlc_txn[0], bob_state_y);
8466 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8467 // it. However, she should, because it now has an invalid parent.
8468 check_spends!(htlc_txn[1], alice_state);
8473 fn test_pre_lockin_no_chan_closed_update() {
8474 // Test that if a peer closes a channel in response to a funding_created message we don't
8475 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8478 // Doing so would imply a channel monitor update before the initial channel monitor
8479 // registration, violating our API guarantees.
8481 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8482 // then opening a second channel with the same funding output as the first (which is not
8483 // rejected because the first channel does not exist in the ChannelManager) and closing it
8484 // before receiving funding_signed.
8485 let chanmon_cfgs = create_chanmon_cfgs(2);
8486 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8487 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8488 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8490 // Create an initial channel
8491 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8492 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8493 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8494 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8495 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8497 // Move the first channel through the funding flow...
8498 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8500 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8501 check_added_monitors!(nodes[0], 0);
8503 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8504 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8505 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8506 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8507 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8511 fn test_htlc_no_detection() {
8512 // This test is a mutation to underscore the detection logic bug we had
8513 // before #653. HTLC value routed is above the remaining balance, thus
8514 // inverting HTLC and `to_remote` output. HTLC will come second and
8515 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8516 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8517 // outputs order detection for correct spending children filtring.
8519 let chanmon_cfgs = create_chanmon_cfgs(2);
8520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8524 // Create some initial channels
8525 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8527 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8528 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8529 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8530 assert_eq!(local_txn[0].input.len(), 1);
8531 assert_eq!(local_txn[0].output.len(), 3);
8532 check_spends!(local_txn[0], chan_1.3);
8534 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8535 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8536 connect_block(&nodes[0], &block);
8537 // We deliberately connect the local tx twice as this should provoke a failure calling
8538 // this test before #653 fix.
8539 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8540 check_closed_broadcast!(nodes[0], true);
8541 check_added_monitors!(nodes[0], 1);
8542 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8543 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8545 let htlc_timeout = {
8546 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8547 assert_eq!(node_txn.len(), 1);
8548 assert_eq!(node_txn[0].input.len(), 1);
8549 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8550 check_spends!(node_txn[0], local_txn[0]);
8554 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8555 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8556 expect_payment_failed!(nodes[0], our_payment_hash, false);
8559 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8560 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8561 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8562 // Carol, Alice would be the upstream node, and Carol the downstream.)
8564 // Steps of the test:
8565 // 1) Alice sends a HTLC to Carol through Bob.
8566 // 2) Carol doesn't settle the HTLC.
8567 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8568 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8569 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8570 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8571 // 5) Carol release the preimage to Bob off-chain.
8572 // 6) Bob claims the offered output on the broadcasted commitment.
8573 let chanmon_cfgs = create_chanmon_cfgs(3);
8574 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8575 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8576 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8578 // Create some initial channels
8579 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8580 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8582 // Steps (1) and (2):
8583 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8584 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8586 // Check that Alice's commitment transaction now contains an output for this HTLC.
8587 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8588 check_spends!(alice_txn[0], chan_ab.3);
8589 assert_eq!(alice_txn[0].output.len(), 2);
8590 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8591 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8592 assert_eq!(alice_txn.len(), 2);
8594 // Steps (3) and (4):
8595 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8596 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8597 let mut force_closing_node = 0; // Alice force-closes
8598 let mut counterparty_node = 1; // Bob if Alice force-closes
8601 if !broadcast_alice {
8602 force_closing_node = 1;
8603 counterparty_node = 0;
8605 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8606 check_closed_broadcast!(nodes[force_closing_node], true);
8607 check_added_monitors!(nodes[force_closing_node], 1);
8608 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8609 if go_onchain_before_fulfill {
8610 let txn_to_broadcast = match broadcast_alice {
8611 true => alice_txn.clone(),
8612 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8614 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8615 if broadcast_alice {
8616 check_closed_broadcast!(nodes[1], true);
8617 check_added_monitors!(nodes[1], 1);
8618 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8623 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8624 // process of removing the HTLC from their commitment transactions.
8625 nodes[2].node.claim_funds(payment_preimage);
8626 check_added_monitors!(nodes[2], 1);
8627 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8629 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8630 assert!(carol_updates.update_add_htlcs.is_empty());
8631 assert!(carol_updates.update_fail_htlcs.is_empty());
8632 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8633 assert!(carol_updates.update_fee.is_none());
8634 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8636 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8637 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8638 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8639 if !go_onchain_before_fulfill && broadcast_alice {
8640 let events = nodes[1].node.get_and_clear_pending_msg_events();
8641 assert_eq!(events.len(), 1);
8643 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8644 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8646 _ => panic!("Unexpected event"),
8649 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8650 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8651 // Carol<->Bob's updated commitment transaction info.
8652 check_added_monitors!(nodes[1], 2);
8654 let events = nodes[1].node.get_and_clear_pending_msg_events();
8655 assert_eq!(events.len(), 2);
8656 let bob_revocation = match events[0] {
8657 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8658 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8661 _ => panic!("Unexpected event"),
8663 let bob_updates = match events[1] {
8664 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8665 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8668 _ => panic!("Unexpected event"),
8671 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8672 check_added_monitors!(nodes[2], 1);
8673 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8674 check_added_monitors!(nodes[2], 1);
8676 let events = nodes[2].node.get_and_clear_pending_msg_events();
8677 assert_eq!(events.len(), 1);
8678 let carol_revocation = match events[0] {
8679 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8680 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8683 _ => panic!("Unexpected event"),
8685 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8686 check_added_monitors!(nodes[1], 1);
8688 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8689 // here's where we put said channel's commitment tx on-chain.
8690 let mut txn_to_broadcast = alice_txn.clone();
8691 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8692 if !go_onchain_before_fulfill {
8693 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8694 // If Bob was the one to force-close, he will have already passed these checks earlier.
8695 if broadcast_alice {
8696 check_closed_broadcast!(nodes[1], true);
8697 check_added_monitors!(nodes[1], 1);
8698 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8700 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8701 if broadcast_alice {
8702 assert_eq!(bob_txn.len(), 1);
8703 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8705 assert_eq!(bob_txn.len(), 2);
8706 check_spends!(bob_txn[0], chan_ab.3);
8711 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8712 // broadcasted commitment transaction.
8714 let script_weight = match broadcast_alice {
8715 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8716 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8718 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8719 // Bob force-closed and broadcasts the commitment transaction along with a
8720 // HTLC-output-claiming transaction.
8721 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8722 if broadcast_alice {
8723 assert_eq!(bob_txn.len(), 1);
8724 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8725 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8727 assert_eq!(bob_txn.len(), 2);
8728 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8729 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8735 fn test_onchain_htlc_settlement_after_close() {
8736 do_test_onchain_htlc_settlement_after_close(true, true);
8737 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8738 do_test_onchain_htlc_settlement_after_close(true, false);
8739 do_test_onchain_htlc_settlement_after_close(false, false);
8743 fn test_duplicate_temporary_channel_id_from_different_peers() {
8744 // Tests that we can accept two different `OpenChannel` requests with the same
8745 // `temporary_channel_id`, as long as they are from different peers.
8746 let chanmon_cfgs = create_chanmon_cfgs(3);
8747 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8748 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8749 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8751 // Create an first channel channel
8752 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8753 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8755 // Create an second channel
8756 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8757 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8759 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8760 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8761 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8763 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8764 // `temporary_channel_id` as they are from different peers.
8765 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8767 let events = nodes[0].node.get_and_clear_pending_msg_events();
8768 assert_eq!(events.len(), 1);
8770 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8771 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8772 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8774 _ => panic!("Unexpected event"),
8778 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8780 let events = nodes[0].node.get_and_clear_pending_msg_events();
8781 assert_eq!(events.len(), 1);
8783 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8784 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8785 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8787 _ => panic!("Unexpected event"),
8793 fn test_duplicate_chan_id() {
8794 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8795 // already open we reject it and keep the old channel.
8797 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8798 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8799 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8800 // updating logic for the existing channel.
8801 let chanmon_cfgs = create_chanmon_cfgs(2);
8802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8806 // Create an initial channel
8807 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8808 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8809 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8810 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()));
8812 // Try to create a second channel with the same temporary_channel_id as the first and check
8813 // that it is rejected.
8814 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8816 let events = nodes[1].node.get_and_clear_pending_msg_events();
8817 assert_eq!(events.len(), 1);
8819 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8820 // Technically, at this point, nodes[1] would be justified in thinking both the
8821 // first (valid) and second (invalid) channels are closed, given they both have
8822 // the same non-temporary channel_id. However, currently we do not, so we just
8823 // move forward with it.
8824 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8825 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8827 _ => panic!("Unexpected event"),
8831 // Move the first channel through the funding flow...
8832 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8834 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8835 check_added_monitors!(nodes[0], 0);
8837 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8838 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8840 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8841 assert_eq!(added_monitors.len(), 1);
8842 assert_eq!(added_monitors[0].0, funding_output);
8843 added_monitors.clear();
8845 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8847 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8849 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8850 let channel_id = funding_outpoint.to_channel_id();
8852 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8855 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8856 // Technically this is allowed by the spec, but we don't support it and there's little reason
8857 // to. Still, it shouldn't cause any other issues.
8858 open_chan_msg.temporary_channel_id = channel_id;
8859 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8861 let events = nodes[1].node.get_and_clear_pending_msg_events();
8862 assert_eq!(events.len(), 1);
8864 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8865 // Technically, at this point, nodes[1] would be justified in thinking both
8866 // channels are closed, but currently we do not, so we just move forward with it.
8867 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8868 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8870 _ => panic!("Unexpected event"),
8874 // Now try to create a second channel which has a duplicate funding output.
8875 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8876 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8877 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8878 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()));
8879 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8881 let (_, funding_created) = {
8882 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8883 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8884 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8885 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8886 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8887 // channelmanager in a possibly nonsense state instead).
8888 let mut as_chan = a_peer_state.outbound_v1_channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8889 let logger = test_utils::TestLogger::new();
8890 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).map_err(|_| ()).unwrap()
8892 check_added_monitors!(nodes[0], 0);
8893 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8894 // At this point we'll look up if the channel_id is present and immediately fail the channel
8895 // without trying to persist the `ChannelMonitor`.
8896 check_added_monitors!(nodes[1], 0);
8898 // ...still, nodes[1] will reject the duplicate channel.
8900 let events = nodes[1].node.get_and_clear_pending_msg_events();
8901 assert_eq!(events.len(), 1);
8903 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8904 // Technically, at this point, nodes[1] would be justified in thinking both
8905 // channels are closed, but currently we do not, so we just move forward with it.
8906 assert_eq!(msg.channel_id, channel_id);
8907 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8909 _ => panic!("Unexpected event"),
8913 // finally, finish creating the original channel and send a payment over it to make sure
8914 // everything is functional.
8915 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8917 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8918 assert_eq!(added_monitors.len(), 1);
8919 assert_eq!(added_monitors[0].0, funding_output);
8920 added_monitors.clear();
8922 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8924 let events_4 = nodes[0].node.get_and_clear_pending_events();
8925 assert_eq!(events_4.len(), 0);
8926 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8927 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8929 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8930 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8931 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8933 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8937 fn test_error_chans_closed() {
8938 // Test that we properly handle error messages, closing appropriate channels.
8940 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8941 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8942 // we can test various edge cases around it to ensure we don't regress.
8943 let chanmon_cfgs = create_chanmon_cfgs(3);
8944 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8945 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8946 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8948 // Create some initial channels
8949 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8950 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8951 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8953 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8954 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8955 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8957 // Closing a channel from a different peer has no effect
8958 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8959 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8961 // Closing one channel doesn't impact others
8962 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8963 check_added_monitors!(nodes[0], 1);
8964 check_closed_broadcast!(nodes[0], false);
8965 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8966 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8967 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8968 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);
8969 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);
8971 // A null channel ID should close all channels
8972 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8973 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8974 check_added_monitors!(nodes[0], 2);
8975 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
8976 let events = nodes[0].node.get_and_clear_pending_msg_events();
8977 assert_eq!(events.len(), 2);
8979 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8980 assert_eq!(msg.contents.flags & 2, 2);
8982 _ => panic!("Unexpected event"),
8985 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8986 assert_eq!(msg.contents.flags & 2, 2);
8988 _ => panic!("Unexpected event"),
8990 // Note that at this point users of a standard PeerHandler will end up calling
8991 // peer_disconnected.
8992 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8993 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8995 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
8996 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8997 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9001 fn test_invalid_funding_tx() {
9002 // Test that we properly handle invalid funding transactions sent to us from a peer.
9004 // Previously, all other major lightning implementations had failed to properly sanitize
9005 // funding transactions from their counterparties, leading to a multi-implementation critical
9006 // security vulnerability (though we always sanitized properly, we've previously had
9007 // un-released crashes in the sanitization process).
9009 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9010 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9011 // gave up on it. We test this here by generating such a transaction.
9012 let chanmon_cfgs = create_chanmon_cfgs(2);
9013 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9014 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9015 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9017 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9018 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()));
9019 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()));
9021 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9023 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9024 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9025 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9027 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9028 let wit_program_script: Script = wit_program.into();
9029 for output in tx.output.iter_mut() {
9030 // Make the confirmed funding transaction have a bogus script_pubkey
9031 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9034 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9035 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()));
9036 check_added_monitors!(nodes[1], 1);
9037 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9039 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()));
9040 check_added_monitors!(nodes[0], 1);
9041 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9043 let events_1 = nodes[0].node.get_and_clear_pending_events();
9044 assert_eq!(events_1.len(), 0);
9046 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9047 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9048 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9050 let expected_err = "funding tx had wrong script/value or output index";
9051 confirm_transaction_at(&nodes[1], &tx, 1);
9052 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9053 check_added_monitors!(nodes[1], 1);
9054 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9055 assert_eq!(events_2.len(), 1);
9056 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9057 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9058 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9059 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9060 } else { panic!(); }
9061 } else { panic!(); }
9062 assert_eq!(nodes[1].node.list_channels().len(), 0);
9064 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9065 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9066 // as its not 32 bytes long.
9067 let mut spend_tx = Transaction {
9068 version: 2i32, lock_time: PackedLockTime::ZERO,
9069 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9070 previous_output: BitcoinOutPoint {
9074 script_sig: Script::new(),
9075 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9076 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9078 output: vec![TxOut {
9080 script_pubkey: Script::new(),
9083 check_spends!(spend_tx, tx);
9084 mine_transaction(&nodes[1], &spend_tx);
9087 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9088 // In the first version of the chain::Confirm interface, after a refactor was made to not
9089 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9090 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9091 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9092 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9093 // spending transaction until height N+1 (or greater). This was due to the way
9094 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9095 // spending transaction at the height the input transaction was confirmed at, not whether we
9096 // should broadcast a spending transaction at the current height.
9097 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9098 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9099 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9100 // until we learned about an additional block.
9102 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9103 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9104 let chanmon_cfgs = create_chanmon_cfgs(3);
9105 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9106 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9107 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9108 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9110 create_announced_chan_between_nodes(&nodes, 0, 1);
9111 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9112 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9113 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9114 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9116 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9117 check_closed_broadcast!(nodes[1], true);
9118 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9119 check_added_monitors!(nodes[1], 1);
9120 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9121 assert_eq!(node_txn.len(), 1);
9123 let conf_height = nodes[1].best_block_info().1;
9124 if !test_height_before_timelock {
9125 connect_blocks(&nodes[1], 24 * 6);
9127 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9128 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9129 if test_height_before_timelock {
9130 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9131 // generate any events or broadcast any transactions
9132 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9133 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9135 // We should broadcast an HTLC transaction spending our funding transaction first
9136 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9137 assert_eq!(spending_txn.len(), 2);
9138 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9139 check_spends!(spending_txn[1], node_txn[0]);
9140 // We should also generate a SpendableOutputs event with the to_self output (as its
9142 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9143 assert_eq!(descriptor_spend_txn.len(), 1);
9145 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9146 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9147 // additional block built on top of the current chain.
9148 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9149 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9150 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 }]);
9151 check_added_monitors!(nodes[1], 1);
9153 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9154 assert!(updates.update_add_htlcs.is_empty());
9155 assert!(updates.update_fulfill_htlcs.is_empty());
9156 assert_eq!(updates.update_fail_htlcs.len(), 1);
9157 assert!(updates.update_fail_malformed_htlcs.is_empty());
9158 assert!(updates.update_fee.is_none());
9159 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9160 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9161 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9166 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9167 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9168 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9171 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9172 let chanmon_cfgs = create_chanmon_cfgs(2);
9173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9177 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9179 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9180 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9181 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9183 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9186 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9187 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9188 check_added_monitors!(nodes[0], 1);
9189 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9190 assert_eq!(events.len(), 1);
9191 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9192 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9193 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9195 expect_pending_htlcs_forwardable!(nodes[1]);
9196 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9199 // Note that we use a different PaymentId here to allow us to duplicativly pay
9200 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9201 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9202 check_added_monitors!(nodes[0], 1);
9203 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9204 assert_eq!(events.len(), 1);
9205 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9206 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9207 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9208 // At this point, nodes[1] would notice it has too much value for the payment. It will
9209 // assume the second is a privacy attack (no longer particularly relevant
9210 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9211 // the first HTLC delivered above.
9214 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9215 nodes[1].node.process_pending_htlc_forwards();
9217 if test_for_second_fail_panic {
9218 // Now we go fail back the first HTLC from the user end.
9219 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9221 let expected_destinations = vec![
9222 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9223 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9225 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9226 nodes[1].node.process_pending_htlc_forwards();
9228 check_added_monitors!(nodes[1], 1);
9229 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9230 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9233 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9234 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9236 let failure_events = nodes[0].node.get_and_clear_pending_events();
9237 assert_eq!(failure_events.len(), 4);
9238 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9239 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9240 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9241 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9243 // Let the second HTLC fail and claim the first
9244 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9245 nodes[1].node.process_pending_htlc_forwards();
9247 check_added_monitors!(nodes[1], 1);
9248 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9249 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9250 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9252 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9254 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9259 fn test_dup_htlc_second_fail_panic() {
9260 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9261 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9262 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9263 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9264 do_test_dup_htlc_second_rejected(true);
9268 fn test_dup_htlc_second_rejected() {
9269 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9270 // simply reject the second HTLC but are still able to claim the first HTLC.
9271 do_test_dup_htlc_second_rejected(false);
9275 fn test_inconsistent_mpp_params() {
9276 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9277 // such HTLC and allow the second to stay.
9278 let chanmon_cfgs = create_chanmon_cfgs(4);
9279 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9280 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9281 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9283 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9284 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9285 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9286 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9288 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9289 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9290 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9291 assert_eq!(route.paths.len(), 2);
9292 route.paths.sort_by(|path_a, _| {
9293 // Sort the path so that the path through nodes[1] comes first
9294 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9295 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9298 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9300 let cur_height = nodes[0].best_block_info().1;
9301 let payment_id = PaymentId([42; 32]);
9303 let session_privs = {
9304 // We create a fake route here so that we start with three pending HTLCs, which we'll
9305 // ultimately have, just not right away.
9306 let mut dup_route = route.clone();
9307 dup_route.paths.push(route.paths[1].clone());
9308 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9309 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9311 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9312 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9313 &None, session_privs[0]).unwrap();
9314 check_added_monitors!(nodes[0], 1);
9317 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9318 assert_eq!(events.len(), 1);
9319 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9321 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9323 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9324 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9325 check_added_monitors!(nodes[0], 1);
9328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9329 assert_eq!(events.len(), 1);
9330 let payment_event = SendEvent::from_event(events.pop().unwrap());
9332 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9333 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9335 expect_pending_htlcs_forwardable!(nodes[2]);
9336 check_added_monitors!(nodes[2], 1);
9338 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9339 assert_eq!(events.len(), 1);
9340 let payment_event = SendEvent::from_event(events.pop().unwrap());
9342 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9343 check_added_monitors!(nodes[3], 0);
9344 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9346 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9347 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9348 // post-payment_secrets) and fail back the new HTLC.
9350 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9351 nodes[3].node.process_pending_htlc_forwards();
9352 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9353 nodes[3].node.process_pending_htlc_forwards();
9355 check_added_monitors!(nodes[3], 1);
9357 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9358 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9359 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9361 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 }]);
9362 check_added_monitors!(nodes[2], 1);
9364 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9365 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9366 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9368 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9370 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9371 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9372 &None, session_privs[2]).unwrap();
9373 check_added_monitors!(nodes[0], 1);
9375 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9376 assert_eq!(events.len(), 1);
9377 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9379 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9380 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9384 fn test_keysend_payments_to_public_node() {
9385 let chanmon_cfgs = create_chanmon_cfgs(2);
9386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9390 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9391 let network_graph = nodes[0].network_graph.clone();
9392 let payer_pubkey = nodes[0].node.get_our_node_id();
9393 let payee_pubkey = nodes[1].node.get_our_node_id();
9394 let route_params = RouteParameters {
9395 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9396 final_value_msat: 10000,
9398 let scorer = test_utils::TestScorer::new();
9399 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9400 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9402 let test_preimage = PaymentPreimage([42; 32]);
9403 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9404 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9405 check_added_monitors!(nodes[0], 1);
9406 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9407 assert_eq!(events.len(), 1);
9408 let event = events.pop().unwrap();
9409 let path = vec![&nodes[1]];
9410 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9411 claim_payment(&nodes[0], &path, test_preimage);
9415 fn test_keysend_payments_to_private_node() {
9416 let chanmon_cfgs = create_chanmon_cfgs(2);
9417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9419 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9421 let payer_pubkey = nodes[0].node.get_our_node_id();
9422 let payee_pubkey = nodes[1].node.get_our_node_id();
9424 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9425 let route_params = RouteParameters {
9426 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40, false),
9427 final_value_msat: 10000,
9429 let network_graph = nodes[0].network_graph.clone();
9430 let first_hops = nodes[0].node.list_usable_channels();
9431 let scorer = test_utils::TestScorer::new();
9432 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9433 let route = find_route(
9434 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9435 nodes[0].logger, &scorer, &(), &random_seed_bytes
9438 let test_preimage = PaymentPreimage([42; 32]);
9439 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9440 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9441 check_added_monitors!(nodes[0], 1);
9442 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9443 assert_eq!(events.len(), 1);
9444 let event = events.pop().unwrap();
9445 let path = vec![&nodes[1]];
9446 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9447 claim_payment(&nodes[0], &path, test_preimage);
9451 fn test_double_partial_claim() {
9452 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9453 // time out, the sender resends only some of the MPP parts, then the user processes the
9454 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9456 let chanmon_cfgs = create_chanmon_cfgs(4);
9457 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9458 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9459 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9461 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9462 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9463 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9464 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9466 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9467 assert_eq!(route.paths.len(), 2);
9468 route.paths.sort_by(|path_a, _| {
9469 // Sort the path so that the path through nodes[1] comes first
9470 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9471 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9474 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9475 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9476 // amount of time to respond to.
9478 // Connect some blocks to time out the payment
9479 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9480 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9482 let failed_destinations = vec![
9483 HTLCDestination::FailedPayment { payment_hash },
9484 HTLCDestination::FailedPayment { payment_hash },
9486 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9488 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9490 // nodes[1] now retries one of the two paths...
9491 nodes[0].node.send_payment_with_route(&route, payment_hash,
9492 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9493 check_added_monitors!(nodes[0], 2);
9495 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9496 assert_eq!(events.len(), 2);
9497 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9498 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9500 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9501 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9502 nodes[3].node.claim_funds(payment_preimage);
9503 check_added_monitors!(nodes[3], 0);
9504 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9507 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9508 #[derive(Clone, Copy, PartialEq)]
9509 enum ExposureEvent {
9510 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9512 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9514 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9515 AtUpdateFeeOutbound,
9518 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9519 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9522 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9523 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9524 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9525 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9526 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9527 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9528 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9529 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9531 let chanmon_cfgs = create_chanmon_cfgs(2);
9532 let mut config = test_default_channel_config();
9533 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9536 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9538 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9539 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9540 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9541 open_channel.max_accepted_htlcs = 60;
9543 open_channel.dust_limit_satoshis = 546;
9545 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9546 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9547 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9549 let opt_anchors = false;
9551 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9554 let mut node_0_per_peer_lock;
9555 let mut node_0_peer_state_lock;
9556 let mut chan = get_outbound_v1_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9557 chan.context.holder_dust_limit_satoshis = 546;
9560 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9561 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()));
9562 check_added_monitors!(nodes[1], 1);
9563 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9565 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()));
9566 check_added_monitors!(nodes[0], 1);
9567 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9569 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9570 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9571 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9573 // Fetch a route in advance as we will be unable to once we're unable to send.
9574 let (mut route, payment_hash, _, payment_secret) =
9575 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9577 let dust_buffer_feerate = {
9578 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9579 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9580 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9581 chan.context.get_dust_buffer_feerate(None) as u64
9583 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;
9584 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9586 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;
9587 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9589 let dust_htlc_on_counterparty_tx: u64 = 4;
9590 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9593 if dust_outbound_balance {
9594 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9595 // Outbound dust balance: 4372 sats
9596 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9597 for _ in 0..dust_outbound_htlc_on_holder_tx {
9598 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9599 nodes[0].node.send_payment_with_route(&route, payment_hash,
9600 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9603 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9604 // Inbound dust balance: 4372 sats
9605 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9606 for _ in 0..dust_inbound_htlc_on_holder_tx {
9607 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9611 if dust_outbound_balance {
9612 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9613 // Outbound dust balance: 5000 sats
9614 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9615 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9616 nodes[0].node.send_payment_with_route(&route, payment_hash,
9617 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9620 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9621 // Inbound dust balance: 5000 sats
9622 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9623 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9628 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9629 route.paths[0].hops.last_mut().unwrap().fee_msat =
9630 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9631 // With default dust exposure: 5000 sats
9633 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9634 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9635 ), true, APIError::ChannelUnavailable { .. }, {});
9637 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9638 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9639 ), true, APIError::ChannelUnavailable { .. }, {});
9641 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9642 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 + 1 });
9643 nodes[1].node.send_payment_with_route(&route, payment_hash,
9644 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9645 check_added_monitors!(nodes[1], 1);
9646 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9647 assert_eq!(events.len(), 1);
9648 let payment_event = SendEvent::from_event(events.remove(0));
9649 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9650 // With default dust exposure: 5000 sats
9652 // Outbound dust balance: 6399 sats
9653 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9654 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9655 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);
9657 // Outbound dust balance: 5200 sats
9658 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9659 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9660 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 1,
9661 config.channel_config.max_dust_htlc_exposure_msat), 1);
9663 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9664 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9665 nodes[0].node.send_payment_with_route(&route, payment_hash,
9666 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9668 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9669 *feerate_lock = *feerate_lock * 10;
9671 nodes[0].node.timer_tick_occurred();
9672 check_added_monitors!(nodes[0], 1);
9673 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9676 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9677 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9678 added_monitors.clear();
9682 fn test_max_dust_htlc_exposure() {
9683 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9684 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9685 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9686 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9687 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9688 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9689 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9690 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9691 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9692 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9693 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9694 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9698 fn test_non_final_funding_tx() {
9699 let chanmon_cfgs = create_chanmon_cfgs(2);
9700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9704 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9705 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9706 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9707 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9708 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9710 let best_height = nodes[0].node.best_block.read().unwrap().height();
9712 let chan_id = *nodes[0].network_chan_count.borrow();
9713 let events = nodes[0].node.get_and_clear_pending_events();
9714 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9715 assert_eq!(events.len(), 1);
9716 let mut tx = match events[0] {
9717 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9718 // Timelock the transaction _beyond_ the best client height + 1.
9719 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9720 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9723 _ => panic!("Unexpected event"),
9725 // Transaction should fail as it's evaluated as non-final for propagation.
9726 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9727 Err(APIError::APIMisuseError { err }) => {
9728 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9733 // However, transaction should be accepted if it's in a +1 headroom from best block.
9734 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9735 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9736 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9740 fn accept_busted_but_better_fee() {
9741 // If a peer sends us a fee update that is too low, but higher than our previous channel
9742 // feerate, we should accept it. In the future we may want to consider closing the channel
9743 // later, but for now we only accept the update.
9744 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9749 create_chan_between_nodes(&nodes[0], &nodes[1]);
9751 // Set nodes[1] to expect 5,000 sat/kW.
9753 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9754 *feerate_lock = 5000;
9757 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9759 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9760 *feerate_lock = 1000;
9762 nodes[0].node.timer_tick_occurred();
9763 check_added_monitors!(nodes[0], 1);
9765 let events = nodes[0].node.get_and_clear_pending_msg_events();
9766 assert_eq!(events.len(), 1);
9768 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9769 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9770 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9772 _ => panic!("Unexpected event"),
9775 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9778 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9779 *feerate_lock = 2000;
9781 nodes[0].node.timer_tick_occurred();
9782 check_added_monitors!(nodes[0], 1);
9784 let events = nodes[0].node.get_and_clear_pending_msg_events();
9785 assert_eq!(events.len(), 1);
9787 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9788 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9789 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9791 _ => panic!("Unexpected event"),
9794 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9797 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9798 *feerate_lock = 1000;
9800 nodes[0].node.timer_tick_occurred();
9801 check_added_monitors!(nodes[0], 1);
9803 let events = nodes[0].node.get_and_clear_pending_msg_events();
9804 assert_eq!(events.len(), 1);
9806 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9807 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9808 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9809 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9810 check_closed_broadcast!(nodes[1], true);
9811 check_added_monitors!(nodes[1], 1);
9813 _ => panic!("Unexpected event"),
9817 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9818 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9821 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9822 let min_final_cltv_expiry_delta = 120;
9823 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9824 min_final_cltv_expiry_delta - 2 };
9825 let recv_value = 100_000;
9827 create_chan_between_nodes(&nodes[0], &nodes[1]);
9829 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9830 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9831 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9832 Some(recv_value), Some(min_final_cltv_expiry_delta));
9833 (payment_hash, payment_preimage, payment_secret)
9835 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9836 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9838 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9839 nodes[0].node.send_payment_with_route(&route, payment_hash,
9840 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9841 check_added_monitors!(nodes[0], 1);
9842 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9843 assert_eq!(events.len(), 1);
9844 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9845 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9846 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9847 expect_pending_htlcs_forwardable!(nodes[1]);
9850 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9851 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9853 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9855 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9857 check_added_monitors!(nodes[1], 1);
9859 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9860 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9861 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9863 expect_payment_failed!(nodes[0], payment_hash, true);
9868 fn test_payment_with_custom_min_cltv_expiry_delta() {
9869 do_payment_with_custom_min_final_cltv_expiry(false, false);
9870 do_payment_with_custom_min_final_cltv_expiry(false, true);
9871 do_payment_with_custom_min_final_cltv_expiry(true, false);
9872 do_payment_with_custom_min_final_cltv_expiry(true, true);
9876 fn test_disconnects_peer_awaiting_response_ticks() {
9877 // Tests that nodes which are awaiting on a response critical for channel responsiveness
9878 // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9879 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9880 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9881 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9882 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9884 // Asserts a disconnect event is queued to the user.
9885 let check_disconnect_event = |node: &Node, should_disconnect: bool| {
9886 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
9887 if let MessageSendEvent::HandleError { action, .. } = event {
9888 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
9897 assert_eq!(disconnect_event.is_some(), should_disconnect);
9900 // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
9901 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9902 let check_disconnect = |node: &Node| {
9903 // No disconnect without any timer ticks.
9904 check_disconnect_event(node, false);
9906 // No disconnect with 1 timer tick less than required.
9907 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
9908 node.node.timer_tick_occurred();
9909 check_disconnect_event(node, false);
9912 // Disconnect after reaching the required ticks.
9913 node.node.timer_tick_occurred();
9914 check_disconnect_event(node, true);
9916 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
9917 node.node.timer_tick_occurred();
9918 check_disconnect_event(node, true);
9921 create_chan_between_nodes(&nodes[0], &nodes[1]);
9923 // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
9924 *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
9925 nodes[0].node.timer_tick_occurred();
9926 check_added_monitors!(&nodes[0], 1);
9927 let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
9928 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
9929 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
9930 check_added_monitors!(&nodes[1], 1);
9932 // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
9933 let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
9934 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
9935 check_added_monitors!(&nodes[0], 1);
9936 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
9937 check_added_monitors(&nodes[0], 1);
9939 // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
9940 // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
9941 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9942 let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
9943 check_disconnect(&nodes[1]);
9945 // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
9947 // Note that since the commitment dance didn't complete above, Alice is expected to resend her
9948 // final `RevokeAndACK` to Bob to complete it.
9949 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9950 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
9951 let bob_init = msgs::Init {
9952 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
9954 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
9955 let alice_init = msgs::Init {
9956 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
9958 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
9960 // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
9961 // received Bob's yet, so she should disconnect him after reaching
9962 // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9963 let alice_channel_reestablish = get_event_msg!(
9964 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
9966 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
9967 check_disconnect(&nodes[0]);
9969 // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
9970 let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
9971 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
9972 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9978 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
9980 // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
9981 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9982 nodes[0].node.timer_tick_occurred();
9983 check_disconnect_event(&nodes[0], false);
9986 // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
9987 // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
9988 check_disconnect(&nodes[1]);
9990 // Finally, have Bob process the last message.
9991 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
9992 check_added_monitors(&nodes[1], 1);
9994 // At this point, neither node should attempt to disconnect each other, since they aren't
9995 // waiting on any messages.
9996 for node in &nodes {
9997 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
9998 node.node.timer_tick_occurred();
9999 check_disconnect_event(node, false);