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};
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::{Channel, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{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 = Channel::<EnforcingSigner>::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 -= Channel::<EnforcingSigner>::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 let mut chan = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
183 chan.holder_selected_channel_reserve_satoshis = 0;
184 chan.holder_max_htlc_value_in_flight_msat = 100_000_000;
187 let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
188 let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
189 create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
191 // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
192 // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
193 if send_from_initiator {
194 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
195 // Note that for outbound channels we have to consider the commitment tx fee and the
196 // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
197 // well as an additional HTLC.
198 - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, opt_anchors));
200 send_payment(&nodes[1], &[&nodes[0]], push_amt);
205 fn test_counterparty_no_reserve() {
206 do_test_counterparty_no_reserve(true);
207 do_test_counterparty_no_reserve(false);
211 fn test_async_inbound_update_fee() {
212 let chanmon_cfgs = create_chanmon_cfgs(2);
213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
216 create_announced_chan_between_nodes(&nodes, 0, 1);
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
223 // send (1) commitment_signed -.
224 // <- update_add_htlc/commitment_signed
225 // send (2) RAA (awaiting remote revoke) -.
226 // (1) commitment_signed is delivered ->
227 // .- send (3) RAA (awaiting remote revoke)
228 // (2) RAA is delivered ->
229 // .- send (4) commitment_signed
230 // <- (3) RAA is delivered
231 // send (5) commitment_signed -.
232 // <- (4) commitment_signed is delivered
234 // (5) commitment_signed is delivered ->
236 // (6) RAA is delivered ->
238 // First nodes[0] generates an update_fee
240 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
243 nodes[0].node.timer_tick_occurred();
244 check_added_monitors!(nodes[0], 1);
246 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247 assert_eq!(events_0.len(), 1);
248 let (update_msg, commitment_signed) = match events_0[0] { // (1)
249 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
250 (update_fee.as_ref(), commitment_signed)
252 _ => panic!("Unexpected event"),
255 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
257 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
259 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
260 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
261 check_added_monitors!(nodes[1], 1);
263 let payment_event = {
264 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265 assert_eq!(events_1.len(), 1);
266 SendEvent::from_event(events_1.remove(0))
268 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269 assert_eq!(payment_event.msgs.len(), 1);
271 // ...now when the messages get delivered everyone should be happy
272 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276 check_added_monitors!(nodes[0], 1);
278 // deliver(1), generate (3):
279 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
280 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
281 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[1], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
285 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
286 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
287 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
288 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
289 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
290 assert!(bs_update.update_fee.is_none()); // (4)
291 check_added_monitors!(nodes[1], 1);
293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
294 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
295 assert!(as_update.update_add_htlcs.is_empty()); // (5)
296 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
297 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
298 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
299 assert!(as_update.update_fee.is_none()); // (5)
300 check_added_monitors!(nodes[0], 1);
302 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
303 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
304 // only (6) so get_event_msg's assert(len == 1) passes
305 check_added_monitors!(nodes[0], 1);
307 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
308 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
309 check_added_monitors!(nodes[1], 1);
311 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
312 check_added_monitors!(nodes[0], 1);
314 let events_2 = nodes[0].node.get_and_clear_pending_events();
315 assert_eq!(events_2.len(), 1);
317 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
318 _ => panic!("Unexpected event"),
321 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
322 check_added_monitors!(nodes[1], 1);
326 fn test_update_fee_unordered_raa() {
327 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
328 // crash in an earlier version of the update_fee patch)
329 let chanmon_cfgs = create_chanmon_cfgs(2);
330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
332 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
333 create_announced_chan_between_nodes(&nodes, 0, 1);
336 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
338 // First nodes[0] generates an update_fee
340 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
343 nodes[0].node.timer_tick_occurred();
344 check_added_monitors!(nodes[0], 1);
346 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
347 assert_eq!(events_0.len(), 1);
348 let update_msg = match events_0[0] { // (1)
349 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
352 _ => panic!("Unexpected event"),
355 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
357 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
358 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
359 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
360 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
361 check_added_monitors!(nodes[1], 1);
363 let payment_event = {
364 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
365 assert_eq!(events_1.len(), 1);
366 SendEvent::from_event(events_1.remove(0))
368 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
369 assert_eq!(payment_event.msgs.len(), 1);
371 // ...now when the messages get delivered everyone should be happy
372 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
376 check_added_monitors!(nodes[0], 1);
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
379 check_added_monitors!(nodes[1], 1);
381 // We can't continue, sadly, because our (1) now has a bogus signature
385 fn test_multi_flight_update_fee() {
386 let chanmon_cfgs = create_chanmon_cfgs(2);
387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
389 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
390 create_announced_chan_between_nodes(&nodes, 0, 1);
393 // update_fee/commitment_signed ->
394 // .- send (1) RAA and (2) commitment_signed
395 // update_fee (never committed) ->
397 // We have to manually generate the above update_fee, it is allowed by the protocol but we
398 // don't track which updates correspond to which revoke_and_ack responses so we're in
399 // AwaitingRAA mode and will not generate the update_fee yet.
400 // <- (1) RAA delivered
401 // (3) is generated and send (4) CS -.
402 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
403 // know the per_commitment_point to use for it.
404 // <- (2) commitment_signed delivered
406 // B should send no response here
407 // (4) commitment_signed delivered ->
408 // <- RAA/commitment_signed delivered
411 // First nodes[0] generates an update_fee
414 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
415 initial_feerate = *feerate_lock;
416 *feerate_lock = initial_feerate + 20;
418 nodes[0].node.timer_tick_occurred();
419 check_added_monitors!(nodes[0], 1);
421 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
422 assert_eq!(events_0.len(), 1);
423 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
424 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
425 (update_fee.as_ref().unwrap(), commitment_signed)
427 _ => panic!("Unexpected event"),
430 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
431 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
432 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
433 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
434 check_added_monitors!(nodes[1], 1);
436 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
439 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
440 *feerate_lock = initial_feerate + 40;
442 nodes[0].node.timer_tick_occurred();
443 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
446 // Create the (3) update_fee message that nodes[0] will generate before it does...
447 let mut update_msg_2 = msgs::UpdateFee {
448 channel_id: update_msg_1.channel_id.clone(),
449 feerate_per_kw: (initial_feerate + 30) as u32,
452 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
454 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
456 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
458 // Deliver (1), generating (3) and (4)
459 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
460 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
461 check_added_monitors!(nodes[0], 1);
462 assert!(as_second_update.update_add_htlcs.is_empty());
463 assert!(as_second_update.update_fulfill_htlcs.is_empty());
464 assert!(as_second_update.update_fail_htlcs.is_empty());
465 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
466 // Check that the update_fee newly generated matches what we delivered:
467 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
468 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
470 // Deliver (2) commitment_signed
471 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
472 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
473 check_added_monitors!(nodes[0], 1);
474 // No commitment_signed so get_event_msg's assert(len == 1) passes
476 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
477 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
478 check_added_monitors!(nodes[1], 1);
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
482 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
487 check_added_monitors!(nodes[0], 1);
489 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
490 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
491 // No commitment_signed so get_event_msg's assert(len == 1) passes
492 check_added_monitors!(nodes[0], 1);
494 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
495 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
496 check_added_monitors!(nodes[1], 1);
499 fn do_test_sanity_on_in_flight_opens(steps: u8) {
500 // Previously, we had issues deserializing channels when we hadn't connected the first block
501 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
502 // serialization round-trips and simply do steps towards opening a channel and then drop the
505 let chanmon_cfgs = create_chanmon_cfgs(2);
506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
508 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
510 if steps & 0b1000_0000 != 0{
511 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
512 connect_block(&nodes[0], &block);
513 connect_block(&nodes[1], &block);
516 if steps & 0x0f == 0 { return; }
517 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
518 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
520 if steps & 0x0f == 1 { return; }
521 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
522 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
524 if steps & 0x0f == 2 { return; }
525 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
527 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
529 if steps & 0x0f == 3 { return; }
530 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
531 check_added_monitors!(nodes[0], 0);
532 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
534 if steps & 0x0f == 4 { return; }
535 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
537 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
538 assert_eq!(added_monitors.len(), 1);
539 assert_eq!(added_monitors[0].0, funding_output);
540 added_monitors.clear();
542 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
544 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
546 if steps & 0x0f == 5 { return; }
547 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
549 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
550 assert_eq!(added_monitors.len(), 1);
551 assert_eq!(added_monitors[0].0, funding_output);
552 added_monitors.clear();
555 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
556 let events_4 = nodes[0].node.get_and_clear_pending_events();
557 assert_eq!(events_4.len(), 0);
559 if steps & 0x0f == 6 { return; }
560 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
562 if steps & 0x0f == 7 { return; }
563 confirm_transaction_at(&nodes[0], &tx, 2);
564 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
565 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
566 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
570 fn test_sanity_on_in_flight_opens() {
571 do_test_sanity_on_in_flight_opens(0);
572 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
573 do_test_sanity_on_in_flight_opens(1);
574 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
575 do_test_sanity_on_in_flight_opens(2);
576 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
577 do_test_sanity_on_in_flight_opens(3);
578 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
579 do_test_sanity_on_in_flight_opens(4);
580 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
581 do_test_sanity_on_in_flight_opens(5);
582 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
583 do_test_sanity_on_in_flight_opens(6);
584 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
585 do_test_sanity_on_in_flight_opens(7);
586 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
587 do_test_sanity_on_in_flight_opens(8);
588 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
592 fn test_update_fee_vanilla() {
593 let chanmon_cfgs = create_chanmon_cfgs(2);
594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
597 create_announced_chan_between_nodes(&nodes, 0, 1);
600 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
603 nodes[0].node.timer_tick_occurred();
604 check_added_monitors!(nodes[0], 1);
606 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
607 assert_eq!(events_0.len(), 1);
608 let (update_msg, commitment_signed) = match events_0[0] {
609 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 } } => {
610 (update_fee.as_ref(), commitment_signed)
612 _ => panic!("Unexpected event"),
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
616 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
617 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
618 check_added_monitors!(nodes[1], 1);
620 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
621 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
622 check_added_monitors!(nodes[0], 1);
624 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
625 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
626 // No commitment_signed so get_event_msg's assert(len == 1) passes
627 check_added_monitors!(nodes[0], 1);
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
630 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
631 check_added_monitors!(nodes[1], 1);
635 fn test_update_fee_that_funder_cannot_afford() {
636 let chanmon_cfgs = create_chanmon_cfgs(2);
637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640 let channel_value = 5000;
642 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
643 let channel_id = chan.2;
644 let secp_ctx = Secp256k1::new();
645 let default_config = UserConfig::default();
646 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
648 let opt_anchors = false;
650 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
651 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
652 // calculate two different feerates here - the expected local limit as well as the expected
654 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;
655 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(opt_anchors)) as u32;
657 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
658 *feerate_lock = feerate;
660 nodes[0].node.timer_tick_occurred();
661 check_added_monitors!(nodes[0], 1);
662 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
666 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
668 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
670 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
672 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
673 assert_eq!(commitment_tx.output.len(), 2);
674 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, opt_anchors) / 1000;
675 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
676 actual_fee = channel_value - actual_fee;
677 assert_eq!(total_fee, actual_fee);
681 // Increment the feerate by a small constant, accounting for rounding errors
682 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
685 nodes[0].node.timer_tick_occurred();
686 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
687 check_added_monitors!(nodes[0], 0);
689 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
691 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
692 // needed to sign the new commitment tx and (2) sign the new commitment tx.
693 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
694 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
695 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
696 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
697 let chan_signer = local_chan.get_signer();
698 let pubkeys = chan_signer.pubkeys();
699 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
700 pubkeys.funding_pubkey)
702 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
703 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
704 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
705 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
706 let chan_signer = remote_chan.get_signer();
707 let pubkeys = chan_signer.pubkeys();
708 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
709 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
710 pubkeys.funding_pubkey)
713 // Assemble the set of keys we can use for signatures for our commitment_signed message.
714 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
715 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
718 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
719 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
720 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
721 let local_chan_signer = local_chan.get_signer();
722 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
723 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
724 INITIAL_COMMITMENT_NUMBER - 1,
726 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, opt_anchors) / 1000,
727 opt_anchors, local_funding, remote_funding,
728 commit_tx_keys.clone(),
729 non_buffer_feerate + 4,
731 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
733 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
736 let commit_signed_msg = msgs::CommitmentSigned {
739 htlc_signatures: res.1,
741 partial_signature_with_nonce: None,
744 let update_fee = msgs::UpdateFee {
746 feerate_per_kw: non_buffer_feerate + 4,
749 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
751 //While producing the commitment_signed response after handling a received update_fee request the
752 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
753 //Should produce and error.
754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
755 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
756 check_added_monitors!(nodes[1], 1);
757 check_closed_broadcast!(nodes[1], true);
758 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
762 fn test_update_fee_with_fundee_update_add_htlc() {
763 let chanmon_cfgs = create_chanmon_cfgs(2);
764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
766 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
770 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
773 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
776 nodes[0].node.timer_tick_occurred();
777 check_added_monitors!(nodes[0], 1);
779 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
780 assert_eq!(events_0.len(), 1);
781 let (update_msg, commitment_signed) = match events_0[0] {
782 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 } } => {
783 (update_fee.as_ref(), commitment_signed)
785 _ => panic!("Unexpected event"),
787 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
788 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
789 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 check_added_monitors!(nodes[1], 1);
792 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
794 // nothing happens since node[1] is in AwaitingRemoteRevoke
795 nodes[1].node.send_payment_with_route(&route, our_payment_hash,
796 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
798 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
799 assert_eq!(added_monitors.len(), 0);
800 added_monitors.clear();
802 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
803 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
804 // node[1] has nothing to do
806 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
807 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
808 check_added_monitors!(nodes[0], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
811 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
812 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 check_added_monitors!(nodes[0], 1);
814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
815 check_added_monitors!(nodes[1], 1);
816 // AwaitingRemoteRevoke ends here
818 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
819 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
820 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
821 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
822 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
823 assert_eq!(commitment_update.update_fee.is_none(), true);
825 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
826 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
827 check_added_monitors!(nodes[0], 1);
828 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
831 check_added_monitors!(nodes[1], 1);
832 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
834 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
835 check_added_monitors!(nodes[1], 1);
836 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
837 // No commitment_signed so get_event_msg's assert(len == 1) passes
839 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
840 check_added_monitors!(nodes[0], 1);
841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
843 expect_pending_htlcs_forwardable!(nodes[0]);
845 let events = nodes[0].node.get_and_clear_pending_events();
846 assert_eq!(events.len(), 1);
848 Event::PaymentClaimable { .. } => { },
849 _ => panic!("Unexpected event"),
852 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
854 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
855 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
856 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
857 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
858 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
862 fn test_update_fee() {
863 let chanmon_cfgs = create_chanmon_cfgs(2);
864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
866 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
867 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
868 let channel_id = chan.2;
871 // (1) update_fee/commitment_signed ->
872 // <- (2) revoke_and_ack
873 // .- send (3) commitment_signed
874 // (4) update_fee/commitment_signed ->
875 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
876 // <- (3) commitment_signed delivered
877 // send (6) revoke_and_ack -.
878 // <- (5) deliver revoke_and_ack
879 // (6) deliver revoke_and_ack ->
880 // .- send (7) commitment_signed in response to (4)
881 // <- (7) deliver commitment_signed
884 // Create and deliver (1)...
887 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
888 feerate = *feerate_lock;
889 *feerate_lock = feerate + 20;
891 nodes[0].node.timer_tick_occurred();
892 check_added_monitors!(nodes[0], 1);
894 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
895 assert_eq!(events_0.len(), 1);
896 let (update_msg, commitment_signed) = match events_0[0] {
897 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 } } => {
898 (update_fee.as_ref(), commitment_signed)
900 _ => panic!("Unexpected event"),
902 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
904 // Generate (2) and (3):
905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
906 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
907 check_added_monitors!(nodes[1], 1);
910 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
912 check_added_monitors!(nodes[0], 1);
914 // Create and deliver (4)...
916 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
917 *feerate_lock = feerate + 30;
919 nodes[0].node.timer_tick_occurred();
920 check_added_monitors!(nodes[0], 1);
921 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
922 assert_eq!(events_0.len(), 1);
923 let (update_msg, commitment_signed) = match events_0[0] {
924 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 } } => {
925 (update_fee.as_ref(), commitment_signed)
927 _ => panic!("Unexpected event"),
930 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
931 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
932 check_added_monitors!(nodes[1], 1);
934 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
935 // No commitment_signed so get_event_msg's assert(len == 1) passes
937 // Handle (3), creating (6):
938 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
939 check_added_monitors!(nodes[0], 1);
940 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
941 // No commitment_signed so get_event_msg's assert(len == 1) passes
944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
946 check_added_monitors!(nodes[0], 1);
948 // Deliver (6), creating (7):
949 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
950 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
951 assert!(commitment_update.update_add_htlcs.is_empty());
952 assert!(commitment_update.update_fulfill_htlcs.is_empty());
953 assert!(commitment_update.update_fail_htlcs.is_empty());
954 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
955 assert!(commitment_update.update_fee.is_none());
956 check_added_monitors!(nodes[1], 1);
959 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
960 check_added_monitors!(nodes[0], 1);
961 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
962 // No commitment_signed so get_event_msg's assert(len == 1) passes
964 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
965 check_added_monitors!(nodes[1], 1);
966 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
968 assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
969 assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
970 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
971 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
972 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
976 fn fake_network_test() {
977 // Simple test which builds a network of ChannelManagers, connects them to each other, and
978 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
979 let chanmon_cfgs = create_chanmon_cfgs(4);
980 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
981 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
982 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
984 // Create some initial channels
985 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
986 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
987 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
989 // Rebalance the network a bit by relaying one payment through all the channels...
990 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
991 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
992 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
993 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 // Send some more payments
996 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
997 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
998 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1000 // Test failure packets
1001 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1002 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1004 // Add a new channel that skips 3
1005 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1007 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1008 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1009 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1010 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1011 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1012 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 // Do some rebalance loop payments, simultaneously
1016 let mut hops = Vec::with_capacity(3);
1017 hops.push(RouteHop {
1018 pubkey: nodes[2].node.get_our_node_id(),
1019 node_features: NodeFeatures::empty(),
1020 short_channel_id: chan_2.0.contents.short_channel_id,
1021 channel_features: ChannelFeatures::empty(),
1023 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1025 hops.push(RouteHop {
1026 pubkey: nodes[3].node.get_our_node_id(),
1027 node_features: NodeFeatures::empty(),
1028 short_channel_id: chan_3.0.contents.short_channel_id,
1029 channel_features: ChannelFeatures::empty(),
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 node_features: nodes[1].node.node_features(),
1036 short_channel_id: chan_4.0.contents.short_channel_id,
1037 channel_features: nodes[1].node.channel_features(),
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 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;
1042 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;
1043 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;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 node_features: NodeFeatures::empty(),
1049 short_channel_id: chan_4.0.contents.short_channel_id,
1050 channel_features: ChannelFeatures::empty(),
1052 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1054 hops.push(RouteHop {
1055 pubkey: nodes[2].node.get_our_node_id(),
1056 node_features: NodeFeatures::empty(),
1057 short_channel_id: chan_3.0.contents.short_channel_id,
1058 channel_features: ChannelFeatures::empty(),
1060 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1062 hops.push(RouteHop {
1063 pubkey: nodes[1].node.get_our_node_id(),
1064 node_features: nodes[1].node.node_features(),
1065 short_channel_id: chan_2.0.contents.short_channel_id,
1066 channel_features: nodes[1].node.channel_features(),
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 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;
1071 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;
1072 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;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1078 // Close down the channels...
1079 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1080 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1081 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1082 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1083 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1084 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1085 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1086 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1087 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1088 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1089 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1090 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1094 fn holding_cell_htlc_counting() {
1095 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1096 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1097 // commitment dance rounds.
1098 let chanmon_cfgs = create_chanmon_cfgs(3);
1099 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1100 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1101 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1102 create_announced_chan_between_nodes(&nodes, 0, 1);
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1105 // Fetch a route in advance as we will be unable to once we're unable to send.
1106 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1108 let mut payments = Vec::new();
1110 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1111 nodes[1].node.send_payment_with_route(&route, payment_hash,
1112 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1113 payments.push((payment_preimage, payment_hash));
1115 check_added_monitors!(nodes[1], 1);
1117 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1118 assert_eq!(events.len(), 1);
1119 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1120 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1122 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1123 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1126 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1127 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1128 ), true, APIError::ChannelUnavailable { ref err },
1129 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1130 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1131 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
1134 // This should also be true if we try to forward a payment.
1135 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1137 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1138 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1139 check_added_monitors!(nodes[0], 1);
1142 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1143 assert_eq!(events.len(), 1);
1144 let payment_event = SendEvent::from_event(events.pop().unwrap());
1145 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1147 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1148 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1149 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1150 // fails), the second will process the resulting failure and fail the HTLC backward.
1151 expect_pending_htlcs_forwardable!(nodes[1]);
1152 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1153 check_added_monitors!(nodes[1], 1);
1155 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1156 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1157 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1159 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1161 // Now forward all the pending HTLCs and claim them back
1162 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1163 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1164 check_added_monitors!(nodes[2], 1);
1166 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1167 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1168 check_added_monitors!(nodes[1], 1);
1169 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1171 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1172 check_added_monitors!(nodes[1], 1);
1173 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1175 for ref update in as_updates.update_add_htlcs.iter() {
1176 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1178 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1179 check_added_monitors!(nodes[2], 1);
1180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1181 check_added_monitors!(nodes[2], 1);
1182 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1184 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1185 check_added_monitors!(nodes[1], 1);
1186 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1187 check_added_monitors!(nodes[1], 1);
1188 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1190 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1191 check_added_monitors!(nodes[2], 1);
1193 expect_pending_htlcs_forwardable!(nodes[2]);
1195 let events = nodes[2].node.get_and_clear_pending_events();
1196 assert_eq!(events.len(), payments.len());
1197 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1199 &Event::PaymentClaimable { ref payment_hash, .. } => {
1200 assert_eq!(*payment_hash, *hash);
1202 _ => panic!("Unexpected event"),
1206 for (preimage, _) in payments.drain(..) {
1207 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1210 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1214 fn duplicate_htlc_test() {
1215 // Test that we accept duplicate payment_hash HTLCs across the network and that
1216 // claiming/failing them are all separate and don't affect each other
1217 let chanmon_cfgs = create_chanmon_cfgs(6);
1218 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1219 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1220 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1222 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1223 create_announced_chan_between_nodes(&nodes, 0, 3);
1224 create_announced_chan_between_nodes(&nodes, 1, 3);
1225 create_announced_chan_between_nodes(&nodes, 2, 3);
1226 create_announced_chan_between_nodes(&nodes, 3, 4);
1227 create_announced_chan_between_nodes(&nodes, 3, 5);
1229 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1231 *nodes[0].network_payment_count.borrow_mut() -= 1;
1232 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1234 *nodes[0].network_payment_count.borrow_mut() -= 1;
1235 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1237 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1238 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1239 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1243 fn test_duplicate_htlc_different_direction_onchain() {
1244 // Test that ChannelMonitor doesn't generate 2 preimage txn
1245 // when we have 2 HTLCs with same preimage that go across a node
1246 // in opposite directions, even with the same payment secret.
1247 let chanmon_cfgs = create_chanmon_cfgs(2);
1248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1250 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1252 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1255 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1257 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1259 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1260 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1261 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1263 // Provide preimage to node 0 by claiming payment
1264 nodes[0].node.claim_funds(payment_preimage);
1265 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1266 check_added_monitors!(nodes[0], 1);
1268 // Broadcast node 1 commitment txn
1269 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1271 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1272 let mut has_both_htlcs = 0; // check htlcs match ones committed
1273 for outp in remote_txn[0].output.iter() {
1274 if outp.value == 800_000 / 1000 {
1275 has_both_htlcs += 1;
1276 } else if outp.value == 900_000 / 1000 {
1277 has_both_htlcs += 1;
1280 assert_eq!(has_both_htlcs, 2);
1282 mine_transaction(&nodes[0], &remote_txn[0]);
1283 check_added_monitors!(nodes[0], 1);
1284 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1285 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1287 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288 assert_eq!(claim_txn.len(), 3);
1290 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1291 check_spends!(claim_txn[1], remote_txn[0]);
1292 check_spends!(claim_txn[2], remote_txn[0]);
1293 let preimage_tx = &claim_txn[0];
1294 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1295 (&claim_txn[1], &claim_txn[2])
1297 (&claim_txn[2], &claim_txn[1])
1300 assert_eq!(preimage_tx.input.len(), 1);
1301 assert_eq!(preimage_bump_tx.input.len(), 1);
1303 assert_eq!(preimage_tx.input.len(), 1);
1304 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1305 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1307 assert_eq!(timeout_tx.input.len(), 1);
1308 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1309 check_spends!(timeout_tx, remote_txn[0]);
1310 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1312 let events = nodes[0].node.get_and_clear_pending_msg_events();
1313 assert_eq!(events.len(), 3);
1316 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1317 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1318 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1319 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1321 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1322 assert!(update_add_htlcs.is_empty());
1323 assert!(update_fail_htlcs.is_empty());
1324 assert_eq!(update_fulfill_htlcs.len(), 1);
1325 assert!(update_fail_malformed_htlcs.is_empty());
1326 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1328 _ => panic!("Unexpected event"),
1334 fn test_basic_channel_reserve() {
1335 let chanmon_cfgs = create_chanmon_cfgs(2);
1336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1339 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1341 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1342 let channel_reserve = chan_stat.channel_reserve_msat;
1344 // The 2* and +1 are for the fee spike reserve.
1345 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, get_opt_anchors!(nodes[0], nodes[1], chan.2));
1346 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1347 let (mut route, our_payment_hash, _, our_payment_secret) =
1348 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1349 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1350 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1351 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1353 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1355 &APIError::ChannelUnavailable{ref err} =>
1356 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1357 _ => panic!("Unexpected error variant"),
1360 _ => panic!("Unexpected error variant"),
1362 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1363 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 1);
1365 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1369 fn test_fee_spike_violation_fails_htlc() {
1370 let chanmon_cfgs = create_chanmon_cfgs(2);
1371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1374 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1376 let (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,
1398 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1400 // Now manually create the commitment_signed message corresponding to the update_add
1401 // nodes[0] just sent. In the code for construction of this message, "local" refers
1402 // to the sender of the message, and "remote" refers to the receiver.
1404 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1406 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1408 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1409 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1410 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1411 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1412 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1413 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1414 let chan_signer = local_chan.get_signer();
1415 // Make the signer believe we validated another commitment, so we can release the secret
1416 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1418 let pubkeys = chan_signer.pubkeys();
1419 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1420 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1421 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1422 chan_signer.pubkeys().funding_pubkey)
1424 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1425 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1426 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1427 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1428 let chan_signer = remote_chan.get_signer();
1429 let pubkeys = chan_signer.pubkeys();
1430 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1431 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1432 chan_signer.pubkeys().funding_pubkey)
1435 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1436 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1437 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1439 // Build the remote commitment transaction so we can sign it, and then later use the
1440 // signature for the commitment_signed message.
1441 let local_chan_balance = 1313;
1443 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1445 amount_msat: 3460001,
1446 cltv_expiry: htlc_cltv,
1448 transaction_output_index: Some(1),
1451 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1454 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1455 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1456 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1457 let local_chan_signer = local_chan.get_signer();
1458 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1462 local_chan.opt_anchors(), local_funding, remote_funding,
1463 commit_tx_keys.clone(),
1465 &mut vec![(accepted_htlc_info, ())],
1466 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1468 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1471 let commit_signed_msg = msgs::CommitmentSigned {
1474 htlc_signatures: res.1,
1476 partial_signature_with_nonce: None,
1479 // Send the commitment_signed message to the nodes[1].
1480 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1481 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1483 // Send the RAA to nodes[1].
1484 let raa_msg = msgs::RevokeAndACK {
1486 per_commitment_secret: local_secret,
1487 next_per_commitment_point: next_local_point,
1489 next_local_nonce: None,
1491 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1493 let events = nodes[1].node.get_and_clear_pending_msg_events();
1494 assert_eq!(events.len(), 1);
1495 // Make sure the HTLC failed in the way we expect.
1497 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1498 assert_eq!(update_fail_htlcs.len(), 1);
1499 update_fail_htlcs[0].clone()
1501 _ => panic!("Unexpected event"),
1503 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1504 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1506 check_added_monitors!(nodes[1], 2);
1510 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1511 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1512 // Set the fee rate for the channel very high, to the point where the fundee
1513 // sending any above-dust amount would result in a channel reserve violation.
1514 // In this test we check that we would be prevented from sending an HTLC in
1516 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1519 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1520 let default_config = UserConfig::default();
1521 let opt_anchors = false;
1523 let mut push_amt = 100_000_000;
1524 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1526 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1528 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1530 // Sending exactly enough to hit the reserve amount should be accepted
1531 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1532 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1535 // However one more HTLC should be significantly over the reserve amount and fail.
1536 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1537 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1538 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1539 ), true, APIError::ChannelUnavailable { ref err },
1540 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1541 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1542 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
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 -= Channel::<EnforcingSigner>::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 (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1569 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1570 let secp_ctx = Secp256k1::new();
1571 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1572 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1573 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1574 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1575 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1576 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1577 let msg = msgs::UpdateAddHTLC {
1579 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1580 amount_msat: htlc_msat,
1581 payment_hash: payment_hash,
1582 cltv_expiry: htlc_cltv,
1583 onion_routing_packet: onion_packet,
1586 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1587 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1588 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);
1589 assert_eq!(nodes[0].node.list_channels().len(), 0);
1590 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1591 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1592 check_added_monitors!(nodes[0], 1);
1593 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() });
1597 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1598 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1599 // calculating our commitment transaction fee (this was previously broken).
1600 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1601 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1605 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1606 let default_config = UserConfig::default();
1607 let opt_anchors = false;
1609 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1610 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1611 // transaction fee with 0 HTLCs (183 sats)).
1612 let mut push_amt = 100_000_000;
1613 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1614 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1615 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1617 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1618 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1619 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1620 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1621 // commitment transaction fee.
1622 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1624 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1625 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1626 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1629 // One more than the dust amt should fail, however.
1630 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1631 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1632 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1633 ), true, APIError::ChannelUnavailable { ref err },
1634 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1638 fn test_chan_init_feerate_unaffordability() {
1639 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1640 // channel reserve and feerate requirements.
1641 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1642 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1645 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1646 let default_config = UserConfig::default();
1647 let opt_anchors = false;
1649 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1651 let mut push_amt = 100_000_000;
1652 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1653 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1654 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1656 // During open, we don't have a "counterparty channel reserve" to check against, so that
1657 // requirement only comes into play on the open_channel handling side.
1658 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1659 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1660 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1661 open_channel_msg.push_msat += 1;
1662 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1664 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1665 assert_eq!(msg_events.len(), 1);
1666 match msg_events[0] {
1667 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1668 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1670 _ => panic!("Unexpected event"),
1675 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1676 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1677 // calculating our counterparty's commitment transaction fee (this was previously broken).
1678 let chanmon_cfgs = create_chanmon_cfgs(2);
1679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1681 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1682 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1684 let payment_amt = 46000; // Dust amount
1685 // In the previous code, these first four payments would succeed.
1686 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1693 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1695 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1696 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1698 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1699 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1700 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1701 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1705 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1706 let chanmon_cfgs = create_chanmon_cfgs(3);
1707 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1708 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1709 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1710 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1711 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1714 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1715 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1716 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1717 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1719 // Add a 2* and +1 for the fee spike reserve.
1720 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1721 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;
1722 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1724 // Add a pending HTLC.
1725 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1726 let payment_event_1 = {
1727 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1728 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1729 check_added_monitors!(nodes[0], 1);
1731 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1732 assert_eq!(events.len(), 1);
1733 SendEvent::from_event(events.remove(0))
1735 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1737 // Attempt to trigger a channel reserve violation --> payment failure.
1738 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1739 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;
1740 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1741 let mut route_2 = route_1.clone();
1742 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1744 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1745 let secp_ctx = Secp256k1::new();
1746 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1747 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1748 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1749 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1750 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1751 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1752 let msg = msgs::UpdateAddHTLC {
1755 amount_msat: htlc_msat + 1,
1756 payment_hash: our_payment_hash_1,
1757 cltv_expiry: htlc_cltv,
1758 onion_routing_packet: onion_packet,
1761 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1762 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1763 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1764 assert_eq!(nodes[1].node.list_channels().len(), 1);
1765 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1766 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1767 check_added_monitors!(nodes[1], 1);
1768 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1772 fn test_inbound_outbound_capacity_is_not_zero() {
1773 let chanmon_cfgs = create_chanmon_cfgs(2);
1774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1776 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1777 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1778 let channels0 = node_chanmgrs[0].list_channels();
1779 let channels1 = node_chanmgrs[1].list_channels();
1780 let default_config = UserConfig::default();
1781 assert_eq!(channels0.len(), 1);
1782 assert_eq!(channels1.len(), 1);
1784 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1785 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1786 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1788 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1789 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1792 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1793 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1797 fn test_channel_reserve_holding_cell_htlcs() {
1798 let chanmon_cfgs = create_chanmon_cfgs(3);
1799 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1800 // When this test was written, the default base fee floated based on the HTLC count.
1801 // It is now fixed, so we simply set the fee to the expected value here.
1802 let mut config = test_default_channel_config();
1803 config.channel_config.forwarding_fee_base_msat = 239;
1804 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1805 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1806 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1807 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1809 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1810 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1812 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1813 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1815 macro_rules! expect_forward {
1817 let mut events = $node.node.get_and_clear_pending_msg_events();
1818 assert_eq!(events.len(), 1);
1819 check_added_monitors!($node, 1);
1820 let payment_event = SendEvent::from_event(events.remove(0));
1825 let feemsat = 239; // set above
1826 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1827 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1828 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1830 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1832 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1834 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1835 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1836 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1837 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1838 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1840 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1841 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1842 ), true, APIError::ChannelUnavailable { ref err },
1843 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1844 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1845 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
1848 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1849 // nodes[0]'s wealth
1851 let amt_msat = recv_value_0 + total_fee_msat;
1852 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1853 // Also, ensure that each payment has enough to be over the dust limit to
1854 // ensure it'll be included in each commit tx fee calculation.
1855 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1856 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1857 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1861 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1862 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1863 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1864 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1865 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1867 let (stat01_, stat11_, stat12_, stat22_) = (
1868 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1869 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1870 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1871 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1874 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1875 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1876 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1877 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1878 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1881 // adding pending output.
1882 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1883 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1884 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1885 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1886 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1887 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1888 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1889 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1890 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1892 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1893 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1894 let amt_msat_1 = recv_value_1 + total_fee_msat;
1896 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);
1897 let payment_event_1 = {
1898 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1899 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1900 check_added_monitors!(nodes[0], 1);
1902 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1903 assert_eq!(events.len(), 1);
1904 SendEvent::from_event(events.remove(0))
1906 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1908 // channel reserve test with htlc pending output > 0
1909 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1911 let mut route = route_1.clone();
1912 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1913 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1914 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1915 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1916 ), true, APIError::ChannelUnavailable { ref err },
1917 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1918 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1921 // split the rest to test holding cell
1922 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1923 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1924 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1925 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1927 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1928 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);
1931 // now see if they go through on both sides
1932 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);
1933 // but this will stuck in the holding cell
1934 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1935 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1936 check_added_monitors!(nodes[0], 0);
1937 let events = nodes[0].node.get_and_clear_pending_events();
1938 assert_eq!(events.len(), 0);
1940 // test with outbound holding cell amount > 0
1942 let (mut route, our_payment_hash, _, our_payment_secret) =
1943 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1944 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1945 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1946 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1947 ), true, APIError::ChannelUnavailable { ref err },
1948 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1949 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1950 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put our balance under counterparty-announced channel reserve value", 2);
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().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,
3417 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3419 let events = nodes[0].node.get_and_clear_pending_events();
3420 assert_eq!(events.len(), 3);
3421 // Check that Alice fails backward the pending HTLC from the second payment.
3423 Event::PaymentPathFailed { payment_hash, .. } => {
3424 assert_eq!(payment_hash, failed_payment_hash);
3426 _ => panic!("Unexpected event"),
3429 Event::PaymentFailed { payment_hash, .. } => {
3430 assert_eq!(payment_hash, failed_payment_hash);
3432 _ => panic!("Unexpected event"),
3435 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3436 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3438 _ => panic!("Unexpected event {:?}", events[1]),
3440 check_closed_broadcast!(nodes[0], true);
3441 check_added_monitors!(nodes[0], 1);
3445 fn test_htlc_ignore_latest_remote_commitment() {
3446 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3447 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3448 let chanmon_cfgs = create_chanmon_cfgs(2);
3449 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3450 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3451 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3452 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3453 // We rely on the ability to connect a block redundantly, which isn't allowed via
3454 // `chain::Listen`, so we never run the test if we randomly get assigned that
3458 create_announced_chan_between_nodes(&nodes, 0, 1);
3460 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3461 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3462 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3463 check_closed_broadcast!(nodes[0], true);
3464 check_added_monitors!(nodes[0], 1);
3465 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3467 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3468 assert_eq!(node_txn.len(), 3);
3469 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3471 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3472 connect_block(&nodes[1], &block);
3473 check_closed_broadcast!(nodes[1], true);
3474 check_added_monitors!(nodes[1], 1);
3475 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3477 // Duplicate the connect_block call since this may happen due to other listeners
3478 // registering new transactions
3479 connect_block(&nodes[1], &block);
3483 fn test_force_close_fail_back() {
3484 // Check which HTLCs are failed-backwards on channel force-closure
3485 let chanmon_cfgs = create_chanmon_cfgs(3);
3486 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3487 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3488 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3489 create_announced_chan_between_nodes(&nodes, 0, 1);
3490 create_announced_chan_between_nodes(&nodes, 1, 2);
3492 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3494 let mut payment_event = {
3495 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3496 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3497 check_added_monitors!(nodes[0], 1);
3499 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3500 assert_eq!(events.len(), 1);
3501 SendEvent::from_event(events.remove(0))
3504 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3505 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3507 expect_pending_htlcs_forwardable!(nodes[1]);
3509 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3510 assert_eq!(events_2.len(), 1);
3511 payment_event = SendEvent::from_event(events_2.remove(0));
3512 assert_eq!(payment_event.msgs.len(), 1);
3514 check_added_monitors!(nodes[1], 1);
3515 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3516 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3517 check_added_monitors!(nodes[2], 1);
3518 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3520 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3521 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3522 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3524 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3525 check_closed_broadcast!(nodes[2], true);
3526 check_added_monitors!(nodes[2], 1);
3527 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3529 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3530 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3531 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3532 // back to nodes[1] upon timeout otherwise.
3533 assert_eq!(node_txn.len(), 1);
3537 mine_transaction(&nodes[1], &tx);
3539 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3540 check_closed_broadcast!(nodes[1], true);
3541 check_added_monitors!(nodes[1], 1);
3542 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3544 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3546 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3547 .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);
3549 mine_transaction(&nodes[2], &tx);
3550 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3551 assert_eq!(node_txn.len(), 1);
3552 assert_eq!(node_txn[0].input.len(), 1);
3553 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3554 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3555 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3557 check_spends!(node_txn[0], tx);
3561 fn test_dup_events_on_peer_disconnect() {
3562 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3563 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3564 // as we used to generate the event immediately upon receipt of the payment preimage in the
3565 // update_fulfill_htlc message.
3567 let chanmon_cfgs = create_chanmon_cfgs(2);
3568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3570 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3571 create_announced_chan_between_nodes(&nodes, 0, 1);
3573 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3575 nodes[1].node.claim_funds(payment_preimage);
3576 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3577 check_added_monitors!(nodes[1], 1);
3578 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3579 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3580 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3582 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3583 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3585 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3586 expect_payment_path_successful!(nodes[0]);
3590 fn test_peer_disconnected_before_funding_broadcasted() {
3591 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3592 // before the funding transaction has been broadcasted.
3593 let chanmon_cfgs = create_chanmon_cfgs(2);
3594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3598 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3599 // broadcasted, even though it's created by `nodes[0]`.
3600 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();
3601 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3602 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3603 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3604 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3606 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3607 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3609 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3611 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3612 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3614 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3615 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3618 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3621 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3622 // disconnected before the funding transaction was broadcasted.
3623 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3624 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3626 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3627 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3631 fn test_simple_peer_disconnect() {
3632 // Test that we can reconnect when there are no lost messages
3633 let chanmon_cfgs = create_chanmon_cfgs(3);
3634 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3635 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3636 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3637 create_announced_chan_between_nodes(&nodes, 0, 1);
3638 create_announced_chan_between_nodes(&nodes, 1, 2);
3640 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3641 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3642 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3644 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3645 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3646 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3647 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3649 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3650 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3651 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3653 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3654 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3655 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3656 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3658 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3659 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3661 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3662 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3664 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3666 let events = nodes[0].node.get_and_clear_pending_events();
3667 assert_eq!(events.len(), 4);
3669 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3670 assert_eq!(payment_preimage, payment_preimage_3);
3671 assert_eq!(payment_hash, payment_hash_3);
3673 _ => panic!("Unexpected event"),
3676 Event::PaymentPathSuccessful { .. } => {},
3677 _ => panic!("Unexpected event"),
3680 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3681 assert_eq!(payment_hash, payment_hash_5);
3682 assert!(payment_failed_permanently);
3684 _ => panic!("Unexpected event"),
3687 Event::PaymentFailed { payment_hash, .. } => {
3688 assert_eq!(payment_hash, payment_hash_5);
3690 _ => panic!("Unexpected event"),
3694 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3695 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3698 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3699 // Test that we can reconnect when in-flight HTLC updates get dropped
3700 let chanmon_cfgs = create_chanmon_cfgs(2);
3701 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3702 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3703 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3705 let mut as_channel_ready = None;
3706 let channel_id = if messages_delivered == 0 {
3707 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3708 as_channel_ready = Some(channel_ready);
3709 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3710 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3711 // it before the channel_reestablish message.
3714 create_announced_chan_between_nodes(&nodes, 0, 1).2
3717 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3719 let payment_event = {
3720 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3721 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3722 check_added_monitors!(nodes[0], 1);
3724 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3725 assert_eq!(events.len(), 1);
3726 SendEvent::from_event(events.remove(0))
3728 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3730 if messages_delivered < 2 {
3731 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3734 if messages_delivered >= 3 {
3735 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3736 check_added_monitors!(nodes[1], 1);
3737 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3739 if messages_delivered >= 4 {
3740 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3741 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3742 check_added_monitors!(nodes[0], 1);
3744 if messages_delivered >= 5 {
3745 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3746 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3747 // No commitment_signed so get_event_msg's assert(len == 1) passes
3748 check_added_monitors!(nodes[0], 1);
3750 if messages_delivered >= 6 {
3751 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3752 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3753 check_added_monitors!(nodes[1], 1);
3760 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3761 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3762 if messages_delivered < 3 {
3763 if simulate_broken_lnd {
3764 // lnd has a long-standing bug where they send a channel_ready prior to a
3765 // channel_reestablish if you reconnect prior to channel_ready time.
3767 // Here we simulate that behavior, delivering a channel_ready immediately on
3768 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3769 // in `reconnect_nodes` but we currently don't fail based on that.
3771 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3772 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3774 // Even if the channel_ready messages get exchanged, as long as nothing further was
3775 // received on either side, both sides will need to resend them.
3776 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3777 } else if messages_delivered == 3 {
3778 // nodes[0] still wants its RAA + commitment_signed
3779 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3780 } else if messages_delivered == 4 {
3781 // nodes[0] still wants its commitment_signed
3782 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3783 } else if messages_delivered == 5 {
3784 // nodes[1] still wants its final RAA
3785 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3786 } else if messages_delivered == 6 {
3787 // Everything was delivered...
3788 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3791 let events_1 = nodes[1].node.get_and_clear_pending_events();
3792 if messages_delivered == 0 {
3793 assert_eq!(events_1.len(), 2);
3795 Event::ChannelReady { .. } => { },
3796 _ => panic!("Unexpected event"),
3799 Event::PendingHTLCsForwardable { .. } => { },
3800 _ => panic!("Unexpected event"),
3803 assert_eq!(events_1.len(), 1);
3805 Event::PendingHTLCsForwardable { .. } => { },
3806 _ => panic!("Unexpected event"),
3810 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3811 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3812 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3814 nodes[1].node.process_pending_htlc_forwards();
3816 let events_2 = nodes[1].node.get_and_clear_pending_events();
3817 assert_eq!(events_2.len(), 1);
3819 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3820 assert_eq!(payment_hash_1, *payment_hash);
3821 assert_eq!(amount_msat, 1_000_000);
3822 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3823 assert_eq!(via_channel_id, Some(channel_id));
3825 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3826 assert!(payment_preimage.is_none());
3827 assert_eq!(payment_secret_1, *payment_secret);
3829 _ => panic!("expected PaymentPurpose::InvoicePayment")
3832 _ => panic!("Unexpected event"),
3835 nodes[1].node.claim_funds(payment_preimage_1);
3836 check_added_monitors!(nodes[1], 1);
3837 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3839 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3840 assert_eq!(events_3.len(), 1);
3841 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3842 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3843 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3844 assert!(updates.update_add_htlcs.is_empty());
3845 assert!(updates.update_fail_htlcs.is_empty());
3846 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3847 assert!(updates.update_fail_malformed_htlcs.is_empty());
3848 assert!(updates.update_fee.is_none());
3849 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3851 _ => panic!("Unexpected event"),
3854 if messages_delivered >= 1 {
3855 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3857 let events_4 = nodes[0].node.get_and_clear_pending_events();
3858 assert_eq!(events_4.len(), 1);
3860 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3861 assert_eq!(payment_preimage_1, *payment_preimage);
3862 assert_eq!(payment_hash_1, *payment_hash);
3864 _ => panic!("Unexpected event"),
3867 if messages_delivered >= 2 {
3868 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3869 check_added_monitors!(nodes[0], 1);
3870 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3872 if messages_delivered >= 3 {
3873 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3874 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3875 check_added_monitors!(nodes[1], 1);
3877 if messages_delivered >= 4 {
3878 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3879 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3880 // No commitment_signed so get_event_msg's assert(len == 1) passes
3881 check_added_monitors!(nodes[1], 1);
3883 if messages_delivered >= 5 {
3884 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3885 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3886 check_added_monitors!(nodes[0], 1);
3893 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3894 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3895 if messages_delivered < 2 {
3896 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3897 if messages_delivered < 1 {
3898 expect_payment_sent!(nodes[0], payment_preimage_1);
3900 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3902 } else if messages_delivered == 2 {
3903 // nodes[0] still wants its RAA + commitment_signed
3904 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3905 } else if messages_delivered == 3 {
3906 // nodes[0] still wants its commitment_signed
3907 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3908 } else if messages_delivered == 4 {
3909 // nodes[1] still wants its final RAA
3910 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3911 } else if messages_delivered == 5 {
3912 // Everything was delivered...
3913 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3916 if messages_delivered == 1 || messages_delivered == 2 {
3917 expect_payment_path_successful!(nodes[0]);
3919 if messages_delivered <= 5 {
3920 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3921 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3923 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3925 if messages_delivered > 2 {
3926 expect_payment_path_successful!(nodes[0]);
3929 // Channel should still work fine...
3930 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3931 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3932 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3936 fn test_drop_messages_peer_disconnect_a() {
3937 do_test_drop_messages_peer_disconnect(0, true);
3938 do_test_drop_messages_peer_disconnect(0, false);
3939 do_test_drop_messages_peer_disconnect(1, false);
3940 do_test_drop_messages_peer_disconnect(2, false);
3944 fn test_drop_messages_peer_disconnect_b() {
3945 do_test_drop_messages_peer_disconnect(3, false);
3946 do_test_drop_messages_peer_disconnect(4, false);
3947 do_test_drop_messages_peer_disconnect(5, false);
3948 do_test_drop_messages_peer_disconnect(6, false);
3952 fn test_channel_ready_without_best_block_updated() {
3953 // Previously, if we were offline when a funding transaction was locked in, and then we came
3954 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3955 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3956 // channel_ready immediately instead.
3957 let chanmon_cfgs = create_chanmon_cfgs(2);
3958 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3959 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3960 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3961 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3963 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3965 let conf_height = nodes[0].best_block_info().1 + 1;
3966 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3967 let block_txn = [funding_tx];
3968 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3969 let conf_block_header = nodes[0].get_block_header(conf_height);
3970 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3972 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3973 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3974 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3978 fn test_drop_messages_peer_disconnect_dual_htlc() {
3979 // Test that we can handle reconnecting when both sides of a channel have pending
3980 // commitment_updates when we disconnect.
3981 let chanmon_cfgs = create_chanmon_cfgs(2);
3982 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3983 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3984 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3985 create_announced_chan_between_nodes(&nodes, 0, 1);
3987 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3989 // Now try to send a second payment which will fail to send
3990 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3991 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3992 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3993 check_added_monitors!(nodes[0], 1);
3995 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3996 assert_eq!(events_1.len(), 1);
3998 MessageSendEvent::UpdateHTLCs { .. } => {},
3999 _ => panic!("Unexpected event"),
4002 nodes[1].node.claim_funds(payment_preimage_1);
4003 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4004 check_added_monitors!(nodes[1], 1);
4006 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4007 assert_eq!(events_2.len(), 1);
4009 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 } } => {
4010 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4011 assert!(update_add_htlcs.is_empty());
4012 assert_eq!(update_fulfill_htlcs.len(), 1);
4013 assert!(update_fail_htlcs.is_empty());
4014 assert!(update_fail_malformed_htlcs.is_empty());
4015 assert!(update_fee.is_none());
4017 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4018 let events_3 = nodes[0].node.get_and_clear_pending_events();
4019 assert_eq!(events_3.len(), 1);
4021 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4022 assert_eq!(*payment_preimage, payment_preimage_1);
4023 assert_eq!(*payment_hash, payment_hash_1);
4025 _ => panic!("Unexpected event"),
4028 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4029 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4030 // No commitment_signed so get_event_msg's assert(len == 1) passes
4031 check_added_monitors!(nodes[0], 1);
4033 _ => panic!("Unexpected event"),
4036 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4037 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4039 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
4040 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4041 assert_eq!(reestablish_1.len(), 1);
4042 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
4043 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4044 assert_eq!(reestablish_2.len(), 1);
4046 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4047 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4048 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4049 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4051 assert!(as_resp.0.is_none());
4052 assert!(bs_resp.0.is_none());
4054 assert!(bs_resp.1.is_none());
4055 assert!(bs_resp.2.is_none());
4057 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4059 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4060 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4061 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4062 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4063 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4064 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4065 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4066 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4067 // No commitment_signed so get_event_msg's assert(len == 1) passes
4068 check_added_monitors!(nodes[1], 1);
4070 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4071 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4072 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4073 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4074 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4075 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4076 assert!(bs_second_commitment_signed.update_fee.is_none());
4077 check_added_monitors!(nodes[1], 1);
4079 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4080 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4081 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4082 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4083 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4084 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4085 assert!(as_commitment_signed.update_fee.is_none());
4086 check_added_monitors!(nodes[0], 1);
4088 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4089 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4090 // No commitment_signed so get_event_msg's assert(len == 1) passes
4091 check_added_monitors!(nodes[0], 1);
4093 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4094 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4095 // No commitment_signed so get_event_msg's assert(len == 1) passes
4096 check_added_monitors!(nodes[1], 1);
4098 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4099 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4100 check_added_monitors!(nodes[1], 1);
4102 expect_pending_htlcs_forwardable!(nodes[1]);
4104 let events_5 = nodes[1].node.get_and_clear_pending_events();
4105 assert_eq!(events_5.len(), 1);
4107 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4108 assert_eq!(payment_hash_2, *payment_hash);
4110 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4111 assert!(payment_preimage.is_none());
4112 assert_eq!(payment_secret_2, *payment_secret);
4114 _ => panic!("expected PaymentPurpose::InvoicePayment")
4117 _ => panic!("Unexpected event"),
4120 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4121 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4122 check_added_monitors!(nodes[0], 1);
4124 expect_payment_path_successful!(nodes[0]);
4125 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4128 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4129 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4130 // to avoid our counterparty failing the channel.
4131 let chanmon_cfgs = create_chanmon_cfgs(2);
4132 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4136 create_announced_chan_between_nodes(&nodes, 0, 1);
4138 let our_payment_hash = if send_partial_mpp {
4139 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4140 // Use the utility function send_payment_along_path to send the payment with MPP data which
4141 // indicates there are more HTLCs coming.
4142 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.
4143 let payment_id = PaymentId([42; 32]);
4144 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4145 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4146 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4147 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4148 &None, session_privs[0]).unwrap();
4149 check_added_monitors!(nodes[0], 1);
4150 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4151 assert_eq!(events.len(), 1);
4152 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4153 // hop should *not* yet generate any PaymentClaimable event(s).
4154 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4157 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4160 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4161 connect_block(&nodes[0], &block);
4162 connect_block(&nodes[1], &block);
4163 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4164 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4165 block.header.prev_blockhash = block.block_hash();
4166 connect_block(&nodes[0], &block);
4167 connect_block(&nodes[1], &block);
4170 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4172 check_added_monitors!(nodes[1], 1);
4173 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4174 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4175 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4176 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4177 assert!(htlc_timeout_updates.update_fee.is_none());
4179 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4180 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4181 // 100_000 msat as u64, followed by the height at which we failed back above
4182 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4183 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4184 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4188 fn test_htlc_timeout() {
4189 do_test_htlc_timeout(true);
4190 do_test_htlc_timeout(false);
4193 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4194 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4195 let chanmon_cfgs = create_chanmon_cfgs(3);
4196 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4197 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4198 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4199 create_announced_chan_between_nodes(&nodes, 0, 1);
4200 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4202 // Make sure all nodes are at the same starting height
4203 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4204 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4205 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4207 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4208 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4209 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4210 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4211 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4212 check_added_monitors!(nodes[1], 1);
4214 // Now attempt to route a second payment, which should be placed in the holding cell
4215 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4216 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4217 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4218 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4220 check_added_monitors!(nodes[0], 1);
4221 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4222 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4223 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4224 expect_pending_htlcs_forwardable!(nodes[1]);
4226 check_added_monitors!(nodes[1], 0);
4228 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4229 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4230 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4231 connect_blocks(&nodes[1], 1);
4234 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 }]);
4235 check_added_monitors!(nodes[1], 1);
4236 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4237 assert_eq!(fail_commit.len(), 1);
4238 match fail_commit[0] {
4239 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4240 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4241 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4243 _ => unreachable!(),
4245 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4247 expect_payment_failed!(nodes[1], second_payment_hash, false);
4252 fn test_holding_cell_htlc_add_timeouts() {
4253 do_test_holding_cell_htlc_add_timeouts(false);
4254 do_test_holding_cell_htlc_add_timeouts(true);
4257 macro_rules! check_spendable_outputs {
4258 ($node: expr, $keysinterface: expr) => {
4260 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4261 let mut txn = Vec::new();
4262 let mut all_outputs = Vec::new();
4263 let secp_ctx = Secp256k1::new();
4264 for event in events.drain(..) {
4266 Event::SpendableOutputs { mut outputs } => {
4267 for outp in outputs.drain(..) {
4268 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());
4269 all_outputs.push(outp);
4272 _ => panic!("Unexpected event"),
4275 if all_outputs.len() > 1 {
4276 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) {
4286 fn test_claim_sizeable_push_msat() {
4287 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4288 let chanmon_cfgs = create_chanmon_cfgs(2);
4289 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4290 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4291 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4293 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4294 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4295 check_closed_broadcast!(nodes[1], true);
4296 check_added_monitors!(nodes[1], 1);
4297 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4298 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4299 assert_eq!(node_txn.len(), 1);
4300 check_spends!(node_txn[0], chan.3);
4301 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
4303 mine_transaction(&nodes[1], &node_txn[0]);
4304 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4306 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4307 assert_eq!(spend_txn.len(), 1);
4308 assert_eq!(spend_txn[0].input.len(), 1);
4309 check_spends!(spend_txn[0], node_txn[0]);
4310 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4314 fn test_claim_on_remote_sizeable_push_msat() {
4315 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4316 // to_remote output is encumbered by a P2WPKH
4317 let chanmon_cfgs = create_chanmon_cfgs(2);
4318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4320 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4322 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4323 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4324 check_closed_broadcast!(nodes[0], true);
4325 check_added_monitors!(nodes[0], 1);
4326 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4328 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4329 assert_eq!(node_txn.len(), 1);
4330 check_spends!(node_txn[0], chan.3);
4331 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
4333 mine_transaction(&nodes[1], &node_txn[0]);
4334 check_closed_broadcast!(nodes[1], true);
4335 check_added_monitors!(nodes[1], 1);
4336 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4337 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4339 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4340 assert_eq!(spend_txn.len(), 1);
4341 check_spends!(spend_txn[0], node_txn[0]);
4345 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4346 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4347 // to_remote output is encumbered by a P2WPKH
4349 let chanmon_cfgs = create_chanmon_cfgs(2);
4350 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4351 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4352 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4354 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4355 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4356 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4357 assert_eq!(revoked_local_txn[0].input.len(), 1);
4358 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4360 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4361 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4362 check_closed_broadcast!(nodes[1], true);
4363 check_added_monitors!(nodes[1], 1);
4364 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4366 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4367 mine_transaction(&nodes[1], &node_txn[0]);
4368 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4370 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4371 assert_eq!(spend_txn.len(), 3);
4372 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4373 check_spends!(spend_txn[1], node_txn[0]);
4374 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4378 fn test_static_spendable_outputs_preimage_tx() {
4379 let chanmon_cfgs = create_chanmon_cfgs(2);
4380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4382 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4384 // Create some initial channels
4385 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4387 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4389 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4390 assert_eq!(commitment_tx[0].input.len(), 1);
4391 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4393 // Settle A's commitment tx on B's chain
4394 nodes[1].node.claim_funds(payment_preimage);
4395 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4396 check_added_monitors!(nodes[1], 1);
4397 mine_transaction(&nodes[1], &commitment_tx[0]);
4398 check_added_monitors!(nodes[1], 1);
4399 let events = nodes[1].node.get_and_clear_pending_msg_events();
4401 MessageSendEvent::UpdateHTLCs { .. } => {},
4402 _ => panic!("Unexpected event"),
4405 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4406 _ => panic!("Unexepected event"),
4409 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4410 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4411 assert_eq!(node_txn.len(), 1);
4412 check_spends!(node_txn[0], commitment_tx[0]);
4413 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4415 mine_transaction(&nodes[1], &node_txn[0]);
4416 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4417 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4419 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4420 assert_eq!(spend_txn.len(), 1);
4421 check_spends!(spend_txn[0], node_txn[0]);
4425 fn test_static_spendable_outputs_timeout_tx() {
4426 let chanmon_cfgs = create_chanmon_cfgs(2);
4427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4429 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4431 // Create some initial channels
4432 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4434 // Rebalance the network a bit by relaying one payment through all the channels ...
4435 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4437 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4439 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4440 assert_eq!(commitment_tx[0].input.len(), 1);
4441 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4443 // Settle A's commitment tx on B' chain
4444 mine_transaction(&nodes[1], &commitment_tx[0]);
4445 check_added_monitors!(nodes[1], 1);
4446 let events = nodes[1].node.get_and_clear_pending_msg_events();
4448 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4449 _ => panic!("Unexpected event"),
4451 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4453 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4454 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4455 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4456 check_spends!(node_txn[0], commitment_tx[0].clone());
4457 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4459 mine_transaction(&nodes[1], &node_txn[0]);
4460 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4461 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4462 expect_payment_failed!(nodes[1], our_payment_hash, false);
4464 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4465 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4466 check_spends!(spend_txn[0], commitment_tx[0]);
4467 check_spends!(spend_txn[1], node_txn[0]);
4468 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4472 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4473 let chanmon_cfgs = create_chanmon_cfgs(2);
4474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4476 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4478 // Create some initial channels
4479 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4481 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4482 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4483 assert_eq!(revoked_local_txn[0].input.len(), 1);
4484 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4486 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4488 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4489 check_closed_broadcast!(nodes[1], true);
4490 check_added_monitors!(nodes[1], 1);
4491 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4493 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4494 assert_eq!(node_txn.len(), 1);
4495 assert_eq!(node_txn[0].input.len(), 2);
4496 check_spends!(node_txn[0], revoked_local_txn[0]);
4498 mine_transaction(&nodes[1], &node_txn[0]);
4499 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4501 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4502 assert_eq!(spend_txn.len(), 1);
4503 check_spends!(spend_txn[0], node_txn[0]);
4507 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4508 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4509 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4510 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4511 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4512 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4514 // Create some initial channels
4515 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4517 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4518 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4519 assert_eq!(revoked_local_txn[0].input.len(), 1);
4520 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4522 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4524 // A will generate HTLC-Timeout from revoked commitment tx
4525 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4526 check_closed_broadcast!(nodes[0], true);
4527 check_added_monitors!(nodes[0], 1);
4528 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4529 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4531 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4532 assert_eq!(revoked_htlc_txn.len(), 1);
4533 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4534 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4535 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4536 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4538 // B will generate justice tx from A's revoked commitment/HTLC tx
4539 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4540 check_closed_broadcast!(nodes[1], true);
4541 check_added_monitors!(nodes[1], 1);
4542 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4544 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4545 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4546 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4547 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4548 // transactions next...
4549 assert_eq!(node_txn[0].input.len(), 3);
4550 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4552 assert_eq!(node_txn[1].input.len(), 2);
4553 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4554 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4555 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4557 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4558 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4561 mine_transaction(&nodes[1], &node_txn[1]);
4562 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4564 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4565 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4566 assert_eq!(spend_txn.len(), 1);
4567 assert_eq!(spend_txn[0].input.len(), 1);
4568 check_spends!(spend_txn[0], node_txn[1]);
4572 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4573 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4574 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4577 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4579 // Create some initial channels
4580 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4582 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4583 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4584 assert_eq!(revoked_local_txn[0].input.len(), 1);
4585 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4587 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4588 assert_eq!(revoked_local_txn[0].output.len(), 2);
4590 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4592 // B will generate HTLC-Success from revoked commitment tx
4593 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4594 check_closed_broadcast!(nodes[1], true);
4595 check_added_monitors!(nodes[1], 1);
4596 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4597 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4599 assert_eq!(revoked_htlc_txn.len(), 1);
4600 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4601 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4602 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4604 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4605 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4606 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4608 // A will generate justice tx from B's revoked commitment/HTLC tx
4609 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4610 check_closed_broadcast!(nodes[0], true);
4611 check_added_monitors!(nodes[0], 1);
4612 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4614 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4615 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4617 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4618 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4619 // transactions next...
4620 assert_eq!(node_txn[0].input.len(), 2);
4621 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4622 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4623 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4625 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4626 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4629 assert_eq!(node_txn[1].input.len(), 1);
4630 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4632 mine_transaction(&nodes[0], &node_txn[1]);
4633 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4635 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4636 // didn't try to generate any new transactions.
4638 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4639 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4640 assert_eq!(spend_txn.len(), 3);
4641 assert_eq!(spend_txn[0].input.len(), 1);
4642 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4643 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4644 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4645 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4649 fn test_onchain_to_onchain_claim() {
4650 // Test that in case of channel closure, we detect the state of output and claim HTLC
4651 // on downstream peer's remote commitment tx.
4652 // First, have C claim an HTLC against its own latest commitment transaction.
4653 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4655 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4658 let chanmon_cfgs = create_chanmon_cfgs(3);
4659 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4660 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4661 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4663 // Create some initial channels
4664 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4665 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4667 // Ensure all nodes are at the same height
4668 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4669 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4670 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4671 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4673 // Rebalance the network a bit by relaying one payment through all the channels ...
4674 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4675 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4677 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4678 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4679 check_spends!(commitment_tx[0], chan_2.3);
4680 nodes[2].node.claim_funds(payment_preimage);
4681 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4682 check_added_monitors!(nodes[2], 1);
4683 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4684 assert!(updates.update_add_htlcs.is_empty());
4685 assert!(updates.update_fail_htlcs.is_empty());
4686 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4687 assert!(updates.update_fail_malformed_htlcs.is_empty());
4689 mine_transaction(&nodes[2], &commitment_tx[0]);
4690 check_closed_broadcast!(nodes[2], true);
4691 check_added_monitors!(nodes[2], 1);
4692 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4694 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4695 assert_eq!(c_txn.len(), 1);
4696 check_spends!(c_txn[0], commitment_tx[0]);
4697 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4698 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4699 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4701 // 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
4702 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4703 check_added_monitors!(nodes[1], 1);
4704 let events = nodes[1].node.get_and_clear_pending_events();
4705 assert_eq!(events.len(), 2);
4707 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4708 _ => panic!("Unexpected event"),
4711 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4712 assert_eq!(fee_earned_msat, Some(1000));
4713 assert_eq!(prev_channel_id, Some(chan_1.2));
4714 assert_eq!(claim_from_onchain_tx, true);
4715 assert_eq!(next_channel_id, Some(chan_2.2));
4716 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4718 _ => panic!("Unexpected event"),
4720 check_added_monitors!(nodes[1], 1);
4721 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4722 assert_eq!(msg_events.len(), 3);
4723 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4724 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4726 match nodes_2_event {
4727 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4728 _ => panic!("Unexpected event"),
4731 match nodes_0_event {
4732 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, .. } } => {
4733 assert!(update_add_htlcs.is_empty());
4734 assert!(update_fail_htlcs.is_empty());
4735 assert_eq!(update_fulfill_htlcs.len(), 1);
4736 assert!(update_fail_malformed_htlcs.is_empty());
4737 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4739 _ => panic!("Unexpected event"),
4742 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4743 match msg_events[0] {
4744 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4745 _ => panic!("Unexpected event"),
4748 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4749 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4750 mine_transaction(&nodes[1], &commitment_tx[0]);
4751 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4752 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4753 // ChannelMonitor: HTLC-Success tx
4754 assert_eq!(b_txn.len(), 1);
4755 check_spends!(b_txn[0], commitment_tx[0]);
4756 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4757 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4758 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4760 check_closed_broadcast!(nodes[1], true);
4761 check_added_monitors!(nodes[1], 1);
4765 fn test_duplicate_payment_hash_one_failure_one_success() {
4766 // Topology : A --> B --> C --> D
4767 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4768 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4769 // we forward one of the payments onwards to D.
4770 let chanmon_cfgs = create_chanmon_cfgs(4);
4771 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4772 // When this test was written, the default base fee floated based on the HTLC count.
4773 // It is now fixed, so we simply set the fee to the expected value here.
4774 let mut config = test_default_channel_config();
4775 config.channel_config.forwarding_fee_base_msat = 196;
4776 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4777 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4778 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4780 create_announced_chan_between_nodes(&nodes, 0, 1);
4781 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4782 create_announced_chan_between_nodes(&nodes, 2, 3);
4784 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4785 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4786 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4787 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4788 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4790 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4792 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4793 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4794 // script push size limit so that the below script length checks match
4795 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4796 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4797 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4798 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4799 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4801 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4802 assert_eq!(commitment_txn[0].input.len(), 1);
4803 check_spends!(commitment_txn[0], chan_2.3);
4805 mine_transaction(&nodes[1], &commitment_txn[0]);
4806 check_closed_broadcast!(nodes[1], true);
4807 check_added_monitors!(nodes[1], 1);
4808 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4809 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4811 let htlc_timeout_tx;
4812 { // Extract one of the two HTLC-Timeout transaction
4813 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4814 // ChannelMonitor: timeout tx * 2-or-3
4815 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4817 check_spends!(node_txn[0], commitment_txn[0]);
4818 assert_eq!(node_txn[0].input.len(), 1);
4819 assert_eq!(node_txn[0].output.len(), 1);
4821 if node_txn.len() > 2 {
4822 check_spends!(node_txn[1], commitment_txn[0]);
4823 assert_eq!(node_txn[1].input.len(), 1);
4824 assert_eq!(node_txn[1].output.len(), 1);
4825 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4827 check_spends!(node_txn[2], commitment_txn[0]);
4828 assert_eq!(node_txn[2].input.len(), 1);
4829 assert_eq!(node_txn[2].output.len(), 1);
4830 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4832 check_spends!(node_txn[1], commitment_txn[0]);
4833 assert_eq!(node_txn[1].input.len(), 1);
4834 assert_eq!(node_txn[1].output.len(), 1);
4835 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4838 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4839 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4840 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4841 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4842 if node_txn.len() > 2 {
4843 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4844 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4846 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4850 nodes[2].node.claim_funds(our_payment_preimage);
4851 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4853 mine_transaction(&nodes[2], &commitment_txn[0]);
4854 check_added_monitors!(nodes[2], 2);
4855 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4856 let events = nodes[2].node.get_and_clear_pending_msg_events();
4858 MessageSendEvent::UpdateHTLCs { .. } => {},
4859 _ => panic!("Unexpected event"),
4862 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4863 _ => panic!("Unexepected event"),
4865 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4866 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4867 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4868 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4869 assert_eq!(htlc_success_txn[0].input.len(), 1);
4870 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4871 assert_eq!(htlc_success_txn[1].input.len(), 1);
4872 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4873 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4874 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4876 mine_transaction(&nodes[1], &htlc_timeout_tx);
4877 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4878 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 }]);
4879 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4880 assert!(htlc_updates.update_add_htlcs.is_empty());
4881 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4882 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4883 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4884 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4885 check_added_monitors!(nodes[1], 1);
4887 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4888 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4890 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4892 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4894 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4895 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4896 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4897 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4898 assert!(updates.update_add_htlcs.is_empty());
4899 assert!(updates.update_fail_htlcs.is_empty());
4900 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4901 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4902 assert!(updates.update_fail_malformed_htlcs.is_empty());
4903 check_added_monitors!(nodes[1], 1);
4905 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4906 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4907 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4911 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4912 let chanmon_cfgs = create_chanmon_cfgs(2);
4913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4917 // Create some initial channels
4918 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4920 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4921 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4922 assert_eq!(local_txn.len(), 1);
4923 assert_eq!(local_txn[0].input.len(), 1);
4924 check_spends!(local_txn[0], chan_1.3);
4926 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4927 nodes[1].node.claim_funds(payment_preimage);
4928 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4929 check_added_monitors!(nodes[1], 1);
4931 mine_transaction(&nodes[1], &local_txn[0]);
4932 check_added_monitors!(nodes[1], 1);
4933 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4934 let events = nodes[1].node.get_and_clear_pending_msg_events();
4936 MessageSendEvent::UpdateHTLCs { .. } => {},
4937 _ => panic!("Unexpected event"),
4940 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4941 _ => panic!("Unexepected event"),
4944 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4945 assert_eq!(node_txn.len(), 1);
4946 assert_eq!(node_txn[0].input.len(), 1);
4947 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4948 check_spends!(node_txn[0], local_txn[0]);
4952 mine_transaction(&nodes[1], &node_tx);
4953 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4955 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4956 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4957 assert_eq!(spend_txn.len(), 1);
4958 assert_eq!(spend_txn[0].input.len(), 1);
4959 check_spends!(spend_txn[0], node_tx);
4960 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4963 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4964 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4965 // unrevoked commitment transaction.
4966 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4967 // a remote RAA before they could be failed backwards (and combinations thereof).
4968 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4969 // use the same payment hashes.
4970 // Thus, we use a six-node network:
4975 // And test where C fails back to A/B when D announces its latest commitment transaction
4976 let chanmon_cfgs = create_chanmon_cfgs(6);
4977 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4978 // When this test was written, the default base fee floated based on the HTLC count.
4979 // It is now fixed, so we simply set the fee to the expected value here.
4980 let mut config = test_default_channel_config();
4981 config.channel_config.forwarding_fee_base_msat = 196;
4982 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4983 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4984 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4986 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4987 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4988 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4989 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4990 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4992 // Rebalance and check output sanity...
4993 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4994 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4995 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4997 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4998 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
5000 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
5002 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
5003 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5005 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
5007 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
5009 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5011 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5012 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5014 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());
5016 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());
5019 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5021 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5022 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
5025 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
5027 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5028 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());
5030 // Double-check that six of the new HTLC were added
5031 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5032 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5033 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5034 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5036 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5037 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5038 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5039 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5040 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5041 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5042 check_added_monitors!(nodes[4], 0);
5044 let failed_destinations = vec![
5045 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5046 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5047 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5048 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5050 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5051 check_added_monitors!(nodes[4], 1);
5053 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5054 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5055 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5056 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5057 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5058 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5060 // Fail 3rd below-dust and 7th above-dust HTLCs
5061 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5062 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5063 check_added_monitors!(nodes[5], 0);
5065 let failed_destinations_2 = vec![
5066 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5067 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5069 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5070 check_added_monitors!(nodes[5], 1);
5072 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5073 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5074 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5075 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5077 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5079 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5080 let failed_destinations_3 = vec![
5081 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5082 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5083 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5084 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5085 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5086 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5088 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5089 check_added_monitors!(nodes[3], 1);
5090 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5091 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5092 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5093 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5094 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5095 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5096 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5097 if deliver_last_raa {
5098 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5100 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5103 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5104 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5105 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5106 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5108 // We now broadcast the latest commitment transaction, which *should* result in failures for
5109 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5110 // the non-broadcast above-dust HTLCs.
5112 // Alternatively, we may broadcast the previous commitment transaction, which should only
5113 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5114 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5116 if announce_latest {
5117 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5119 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5121 let events = nodes[2].node.get_and_clear_pending_events();
5122 let close_event = if deliver_last_raa {
5123 assert_eq!(events.len(), 2 + 6);
5124 events.last().clone().unwrap()
5126 assert_eq!(events.len(), 1);
5127 events.last().clone().unwrap()
5130 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5131 _ => panic!("Unexpected event"),
5134 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5135 check_closed_broadcast!(nodes[2], true);
5136 if deliver_last_raa {
5137 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5139 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();
5140 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5142 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5143 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5145 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5148 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5150 check_added_monitors!(nodes[2], 3);
5152 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5153 assert_eq!(cs_msgs.len(), 2);
5154 let mut a_done = false;
5155 for msg in cs_msgs {
5157 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5158 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5159 // should be failed-backwards here.
5160 let target = if *node_id == nodes[0].node.get_our_node_id() {
5161 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5162 for htlc in &updates.update_fail_htlcs {
5163 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 });
5165 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5170 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5171 for htlc in &updates.update_fail_htlcs {
5172 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5174 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5175 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5178 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5179 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5180 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5181 if announce_latest {
5182 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5183 if *node_id == nodes[0].node.get_our_node_id() {
5184 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5187 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5189 _ => panic!("Unexpected event"),
5193 let as_events = nodes[0].node.get_and_clear_pending_events();
5194 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5195 let mut as_failds = HashSet::new();
5196 let mut as_updates = 0;
5197 for event in as_events.iter() {
5198 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5199 assert!(as_failds.insert(*payment_hash));
5200 if *payment_hash != payment_hash_2 {
5201 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5203 assert!(!payment_failed_permanently);
5205 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5208 } else if let &Event::PaymentFailed { .. } = event {
5209 } else { panic!("Unexpected event"); }
5211 assert!(as_failds.contains(&payment_hash_1));
5212 assert!(as_failds.contains(&payment_hash_2));
5213 if announce_latest {
5214 assert!(as_failds.contains(&payment_hash_3));
5215 assert!(as_failds.contains(&payment_hash_5));
5217 assert!(as_failds.contains(&payment_hash_6));
5219 let bs_events = nodes[1].node.get_and_clear_pending_events();
5220 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5221 let mut bs_failds = HashSet::new();
5222 let mut bs_updates = 0;
5223 for event in bs_events.iter() {
5224 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5225 assert!(bs_failds.insert(*payment_hash));
5226 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5227 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5229 assert!(!payment_failed_permanently);
5231 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5234 } else if let &Event::PaymentFailed { .. } = event {
5235 } else { panic!("Unexpected event"); }
5237 assert!(bs_failds.contains(&payment_hash_1));
5238 assert!(bs_failds.contains(&payment_hash_2));
5239 if announce_latest {
5240 assert!(bs_failds.contains(&payment_hash_4));
5242 assert!(bs_failds.contains(&payment_hash_5));
5244 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5245 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5246 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5247 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5248 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5249 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5253 fn test_fail_backwards_latest_remote_announce_a() {
5254 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5258 fn test_fail_backwards_latest_remote_announce_b() {
5259 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5263 fn test_fail_backwards_previous_remote_announce() {
5264 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5265 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5266 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5270 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5271 let chanmon_cfgs = create_chanmon_cfgs(2);
5272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5274 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5276 // Create some initial channels
5277 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5279 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5280 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5281 assert_eq!(local_txn[0].input.len(), 1);
5282 check_spends!(local_txn[0], chan_1.3);
5284 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5285 mine_transaction(&nodes[0], &local_txn[0]);
5286 check_closed_broadcast!(nodes[0], true);
5287 check_added_monitors!(nodes[0], 1);
5288 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5289 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5291 let htlc_timeout = {
5292 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5293 assert_eq!(node_txn.len(), 1);
5294 assert_eq!(node_txn[0].input.len(), 1);
5295 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5296 check_spends!(node_txn[0], local_txn[0]);
5300 mine_transaction(&nodes[0], &htlc_timeout);
5301 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5302 expect_payment_failed!(nodes[0], our_payment_hash, false);
5304 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5305 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5306 assert_eq!(spend_txn.len(), 3);
5307 check_spends!(spend_txn[0], local_txn[0]);
5308 assert_eq!(spend_txn[1].input.len(), 1);
5309 check_spends!(spend_txn[1], htlc_timeout);
5310 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5311 assert_eq!(spend_txn[2].input.len(), 2);
5312 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5313 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5314 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5318 fn test_key_derivation_params() {
5319 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5320 // manager rotation to test that `channel_keys_id` returned in
5321 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5322 // then derive a `delayed_payment_key`.
5324 let chanmon_cfgs = create_chanmon_cfgs(3);
5326 // We manually create the node configuration to backup the seed.
5327 let seed = [42; 32];
5328 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5329 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);
5330 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5331 let scorer = Mutex::new(test_utils::TestScorer::new());
5332 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5333 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)) };
5334 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5335 node_cfgs.remove(0);
5336 node_cfgs.insert(0, node);
5338 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5339 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5341 // Create some initial channels
5342 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5344 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5345 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5346 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5348 // Ensure all nodes are at the same height
5349 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5350 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5351 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5352 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5354 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5355 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5356 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5357 assert_eq!(local_txn_1[0].input.len(), 1);
5358 check_spends!(local_txn_1[0], chan_1.3);
5360 // We check funding pubkey are unique
5361 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]));
5362 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]));
5363 if from_0_funding_key_0 == from_1_funding_key_0
5364 || from_0_funding_key_0 == from_1_funding_key_1
5365 || from_0_funding_key_1 == from_1_funding_key_0
5366 || from_0_funding_key_1 == from_1_funding_key_1 {
5367 panic!("Funding pubkeys aren't unique");
5370 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5371 mine_transaction(&nodes[0], &local_txn_1[0]);
5372 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5373 check_closed_broadcast!(nodes[0], true);
5374 check_added_monitors!(nodes[0], 1);
5375 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5377 let htlc_timeout = {
5378 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5379 assert_eq!(node_txn.len(), 1);
5380 assert_eq!(node_txn[0].input.len(), 1);
5381 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5382 check_spends!(node_txn[0], local_txn_1[0]);
5386 mine_transaction(&nodes[0], &htlc_timeout);
5387 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5388 expect_payment_failed!(nodes[0], our_payment_hash, false);
5390 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5391 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5392 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5393 assert_eq!(spend_txn.len(), 3);
5394 check_spends!(spend_txn[0], local_txn_1[0]);
5395 assert_eq!(spend_txn[1].input.len(), 1);
5396 check_spends!(spend_txn[1], htlc_timeout);
5397 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5398 assert_eq!(spend_txn[2].input.len(), 2);
5399 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5400 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5401 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5405 fn test_static_output_closing_tx() {
5406 let chanmon_cfgs = create_chanmon_cfgs(2);
5407 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5408 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5409 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5411 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5413 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5414 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5416 mine_transaction(&nodes[0], &closing_tx);
5417 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5418 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5420 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5421 assert_eq!(spend_txn.len(), 1);
5422 check_spends!(spend_txn[0], closing_tx);
5424 mine_transaction(&nodes[1], &closing_tx);
5425 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5426 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5428 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5429 assert_eq!(spend_txn.len(), 1);
5430 check_spends!(spend_txn[0], closing_tx);
5433 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5434 let chanmon_cfgs = create_chanmon_cfgs(2);
5435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5437 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5438 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5440 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5442 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5443 // present in B's local commitment transaction, but none of A's commitment transactions.
5444 nodes[1].node.claim_funds(payment_preimage);
5445 check_added_monitors!(nodes[1], 1);
5446 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5448 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5449 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5450 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5452 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5453 check_added_monitors!(nodes[0], 1);
5454 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5455 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5456 check_added_monitors!(nodes[1], 1);
5458 let starting_block = nodes[1].best_block_info();
5459 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5460 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5461 connect_block(&nodes[1], &block);
5462 block.header.prev_blockhash = block.block_hash();
5464 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5465 check_closed_broadcast!(nodes[1], true);
5466 check_added_monitors!(nodes[1], 1);
5467 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5470 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5471 let chanmon_cfgs = create_chanmon_cfgs(2);
5472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5474 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5475 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5477 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5478 nodes[0].node.send_payment_with_route(&route, payment_hash,
5479 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5480 check_added_monitors!(nodes[0], 1);
5482 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5484 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5485 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5486 // to "time out" the HTLC.
5488 let starting_block = nodes[1].best_block_info();
5489 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5491 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5492 connect_block(&nodes[0], &block);
5493 block.header.prev_blockhash = block.block_hash();
5495 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5496 check_closed_broadcast!(nodes[0], true);
5497 check_added_monitors!(nodes[0], 1);
5498 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5501 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5502 let chanmon_cfgs = create_chanmon_cfgs(3);
5503 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5504 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5505 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5506 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5508 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5509 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5510 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5511 // actually revoked.
5512 let htlc_value = if use_dust { 50000 } else { 3000000 };
5513 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5514 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5515 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5516 check_added_monitors!(nodes[1], 1);
5518 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5519 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5520 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5521 check_added_monitors!(nodes[0], 1);
5522 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5523 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5524 check_added_monitors!(nodes[1], 1);
5525 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5526 check_added_monitors!(nodes[1], 1);
5527 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5529 if check_revoke_no_close {
5530 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5531 check_added_monitors!(nodes[0], 1);
5534 let starting_block = nodes[1].best_block_info();
5535 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5536 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5537 connect_block(&nodes[0], &block);
5538 block.header.prev_blockhash = block.block_hash();
5540 if !check_revoke_no_close {
5541 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5542 check_closed_broadcast!(nodes[0], true);
5543 check_added_monitors!(nodes[0], 1);
5544 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5546 expect_payment_failed!(nodes[0], our_payment_hash, true);
5550 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5551 // There are only a few cases to test here:
5552 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5553 // broadcastable commitment transactions result in channel closure,
5554 // * its included in an unrevoked-but-previous remote commitment transaction,
5555 // * its included in the latest remote or local commitment transactions.
5556 // We test each of the three possible commitment transactions individually and use both dust and
5558 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5559 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5560 // tested for at least one of the cases in other tests.
5562 fn htlc_claim_single_commitment_only_a() {
5563 do_htlc_claim_local_commitment_only(true);
5564 do_htlc_claim_local_commitment_only(false);
5566 do_htlc_claim_current_remote_commitment_only(true);
5567 do_htlc_claim_current_remote_commitment_only(false);
5571 fn htlc_claim_single_commitment_only_b() {
5572 do_htlc_claim_previous_remote_commitment_only(true, false);
5573 do_htlc_claim_previous_remote_commitment_only(false, false);
5574 do_htlc_claim_previous_remote_commitment_only(true, true);
5575 do_htlc_claim_previous_remote_commitment_only(false, true);
5580 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5581 let chanmon_cfgs = create_chanmon_cfgs(2);
5582 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5583 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5584 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5585 // Force duplicate randomness for every get-random call
5586 for node in nodes.iter() {
5587 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5590 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5591 let channel_value_satoshis=10000;
5592 let push_msat=10001;
5593 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5594 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5595 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5596 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5598 // Create a second channel with the same random values. This used to panic due to a colliding
5599 // channel_id, but now panics due to a colliding outbound SCID alias.
5600 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5604 fn bolt2_open_channel_sending_node_checks_part2() {
5605 let chanmon_cfgs = create_chanmon_cfgs(2);
5606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5608 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5610 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5611 let channel_value_satoshis=2^24;
5612 let push_msat=10001;
5613 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5615 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5616 let channel_value_satoshis=10000;
5617 // Test when push_msat is equal to 1000 * funding_satoshis.
5618 let push_msat=1000*channel_value_satoshis+1;
5619 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5621 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5622 let channel_value_satoshis=10000;
5623 let push_msat=10001;
5624 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
5625 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5626 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5628 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5629 // 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
5630 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5632 // 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.
5633 assert!(BREAKDOWN_TIMEOUT>0);
5634 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5636 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5637 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5638 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5640 // 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.
5641 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5642 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5643 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5644 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5645 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5649 fn bolt2_open_channel_sane_dust_limit() {
5650 let chanmon_cfgs = create_chanmon_cfgs(2);
5651 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5652 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5653 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5655 let channel_value_satoshis=1000000;
5656 let push_msat=10001;
5657 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5658 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5659 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5660 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5662 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5663 let events = nodes[1].node.get_and_clear_pending_msg_events();
5664 let err_msg = match events[0] {
5665 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5668 _ => panic!("Unexpected event"),
5670 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5673 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5674 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5675 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5676 // is no longer affordable once it's freed.
5678 fn test_fail_holding_cell_htlc_upon_free() {
5679 let chanmon_cfgs = create_chanmon_cfgs(2);
5680 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5681 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5682 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5683 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5685 // First nodes[0] generates an update_fee, setting the channel's
5686 // pending_update_fee.
5688 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5689 *feerate_lock += 20;
5691 nodes[0].node.timer_tick_occurred();
5692 check_added_monitors!(nodes[0], 1);
5694 let events = nodes[0].node.get_and_clear_pending_msg_events();
5695 assert_eq!(events.len(), 1);
5696 let (update_msg, commitment_signed) = match events[0] {
5697 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5698 (update_fee.as_ref(), commitment_signed)
5700 _ => panic!("Unexpected event"),
5703 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5705 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5706 let channel_reserve = chan_stat.channel_reserve_msat;
5707 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5708 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5710 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5711 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5712 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5714 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5715 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5716 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5717 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5718 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5720 // Flush the pending fee update.
5721 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5722 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5723 check_added_monitors!(nodes[1], 1);
5724 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5725 check_added_monitors!(nodes[0], 1);
5727 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5728 // HTLC, but now that the fee has been raised the payment will now fail, causing
5729 // us to surface its failure to the user.
5730 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5731 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5732 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);
5733 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5734 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5735 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5737 // Check that the payment failed to be sent out.
5738 let events = nodes[0].node.get_and_clear_pending_events();
5739 assert_eq!(events.len(), 2);
5741 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5742 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5743 assert_eq!(our_payment_hash.clone(), *payment_hash);
5744 assert_eq!(*payment_failed_permanently, false);
5745 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5747 _ => panic!("Unexpected event"),
5750 &Event::PaymentFailed { ref payment_hash, .. } => {
5751 assert_eq!(our_payment_hash.clone(), *payment_hash);
5753 _ => panic!("Unexpected event"),
5757 // Test that if multiple HTLCs are released from the holding cell and one is
5758 // valid but the other is no longer valid upon release, the valid HTLC can be
5759 // successfully completed while the other one fails as expected.
5761 fn test_free_and_fail_holding_cell_htlcs() {
5762 let chanmon_cfgs = create_chanmon_cfgs(2);
5763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5765 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5766 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5768 // First nodes[0] generates an update_fee, setting the channel's
5769 // pending_update_fee.
5771 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5772 *feerate_lock += 200;
5774 nodes[0].node.timer_tick_occurred();
5775 check_added_monitors!(nodes[0], 1);
5777 let events = nodes[0].node.get_and_clear_pending_msg_events();
5778 assert_eq!(events.len(), 1);
5779 let (update_msg, commitment_signed) = match events[0] {
5780 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5781 (update_fee.as_ref(), commitment_signed)
5783 _ => panic!("Unexpected event"),
5786 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5788 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5789 let channel_reserve = chan_stat.channel_reserve_msat;
5790 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5791 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5793 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5795 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5796 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5797 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5799 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5800 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5801 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5802 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5803 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5804 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5805 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5806 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5807 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5808 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5810 // Flush the pending fee update.
5811 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5812 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5813 check_added_monitors!(nodes[1], 1);
5814 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5815 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5816 check_added_monitors!(nodes[0], 2);
5818 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5819 // but now that the fee has been raised the second payment will now fail, causing us
5820 // to surface its failure to the user. The first payment should succeed.
5821 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5822 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5823 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);
5824 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
5825 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5826 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5828 // Check that the second payment failed to be sent out.
5829 let events = nodes[0].node.get_and_clear_pending_events();
5830 assert_eq!(events.len(), 2);
5832 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5833 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5834 assert_eq!(payment_hash_2.clone(), *payment_hash);
5835 assert_eq!(*payment_failed_permanently, false);
5836 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5838 _ => panic!("Unexpected event"),
5841 &Event::PaymentFailed { ref payment_hash, .. } => {
5842 assert_eq!(payment_hash_2.clone(), *payment_hash);
5844 _ => panic!("Unexpected event"),
5847 // Complete the first payment and the RAA from the fee update.
5848 let (payment_event, send_raa_event) = {
5849 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5850 assert_eq!(msgs.len(), 2);
5851 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5853 let raa = match send_raa_event {
5854 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5855 _ => panic!("Unexpected event"),
5857 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5858 check_added_monitors!(nodes[1], 1);
5859 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5860 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5861 let events = nodes[1].node.get_and_clear_pending_events();
5862 assert_eq!(events.len(), 1);
5864 Event::PendingHTLCsForwardable { .. } => {},
5865 _ => panic!("Unexpected event"),
5867 nodes[1].node.process_pending_htlc_forwards();
5868 let events = nodes[1].node.get_and_clear_pending_events();
5869 assert_eq!(events.len(), 1);
5871 Event::PaymentClaimable { .. } => {},
5872 _ => panic!("Unexpected event"),
5874 nodes[1].node.claim_funds(payment_preimage_1);
5875 check_added_monitors!(nodes[1], 1);
5876 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5878 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5879 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5880 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5881 expect_payment_sent!(nodes[0], payment_preimage_1);
5884 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5885 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5886 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5889 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5890 let chanmon_cfgs = create_chanmon_cfgs(3);
5891 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5892 // Avoid having to include routing fees in calculations
5893 let mut config = test_default_channel_config();
5894 config.channel_config.forwarding_fee_base_msat = 0;
5895 config.channel_config.forwarding_fee_proportional_millionths = 0;
5896 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5897 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5898 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5899 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5901 // First nodes[1] generates an update_fee, setting the channel's
5902 // pending_update_fee.
5904 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5905 *feerate_lock += 20;
5907 nodes[1].node.timer_tick_occurred();
5908 check_added_monitors!(nodes[1], 1);
5910 let events = nodes[1].node.get_and_clear_pending_msg_events();
5911 assert_eq!(events.len(), 1);
5912 let (update_msg, commitment_signed) = match events[0] {
5913 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5914 (update_fee.as_ref(), commitment_signed)
5916 _ => panic!("Unexpected event"),
5919 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5921 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5922 let channel_reserve = chan_stat.channel_reserve_msat;
5923 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5924 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5926 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5927 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5928 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5929 let payment_event = {
5930 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5931 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5932 check_added_monitors!(nodes[0], 1);
5934 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5935 assert_eq!(events.len(), 1);
5937 SendEvent::from_event(events.remove(0))
5939 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5940 check_added_monitors!(nodes[1], 0);
5941 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5942 expect_pending_htlcs_forwardable!(nodes[1]);
5944 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5945 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5947 // Flush the pending fee update.
5948 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5949 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5950 check_added_monitors!(nodes[2], 1);
5951 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5952 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5953 check_added_monitors!(nodes[1], 2);
5955 // A final RAA message is generated to finalize the fee update.
5956 let events = nodes[1].node.get_and_clear_pending_msg_events();
5957 assert_eq!(events.len(), 1);
5959 let raa_msg = match &events[0] {
5960 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5963 _ => panic!("Unexpected event"),
5966 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5967 check_added_monitors!(nodes[2], 1);
5968 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5970 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5971 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5972 assert_eq!(process_htlc_forwards_event.len(), 2);
5973 match &process_htlc_forwards_event[0] {
5974 &Event::PendingHTLCsForwardable { .. } => {},
5975 _ => panic!("Unexpected event"),
5978 // In response, we call ChannelManager's process_pending_htlc_forwards
5979 nodes[1].node.process_pending_htlc_forwards();
5980 check_added_monitors!(nodes[1], 1);
5982 // This causes the HTLC to be failed backwards.
5983 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5984 assert_eq!(fail_event.len(), 1);
5985 let (fail_msg, commitment_signed) = match &fail_event[0] {
5986 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5987 assert_eq!(updates.update_add_htlcs.len(), 0);
5988 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5989 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5990 assert_eq!(updates.update_fail_htlcs.len(), 1);
5991 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5993 _ => panic!("Unexpected event"),
5996 // Pass the failure messages back to nodes[0].
5997 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5998 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6000 // Complete the HTLC failure+removal process.
6001 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6002 check_added_monitors!(nodes[0], 1);
6003 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6004 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6005 check_added_monitors!(nodes[1], 2);
6006 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6007 assert_eq!(final_raa_event.len(), 1);
6008 let raa = match &final_raa_event[0] {
6009 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6010 _ => panic!("Unexpected event"),
6012 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6013 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6014 check_added_monitors!(nodes[0], 1);
6017 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6018 // 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.
6019 //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.
6022 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6023 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6024 let chanmon_cfgs = create_chanmon_cfgs(2);
6025 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6026 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6027 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6028 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6030 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6031 route.paths[0].hops[0].fee_msat = 100;
6033 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6034 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6035 ), true, APIError::ChannelUnavailable { ref err },
6036 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6037 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6038 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send less than their minimum HTLC value", 1);
6042 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6043 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6044 let chanmon_cfgs = create_chanmon_cfgs(2);
6045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6047 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6048 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6050 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6051 route.paths[0].hops[0].fee_msat = 0;
6052 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6053 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6054 true, APIError::ChannelUnavailable { ref err },
6055 assert_eq!(err, "Cannot send 0-msat HTLC"));
6057 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6058 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6062 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6063 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6064 let chanmon_cfgs = create_chanmon_cfgs(2);
6065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6067 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6068 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6070 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6071 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6072 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6073 check_added_monitors!(nodes[0], 1);
6074 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6075 updates.update_add_htlcs[0].amount_msat = 0;
6077 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6078 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6079 check_closed_broadcast!(nodes[1], true).unwrap();
6080 check_added_monitors!(nodes[1], 1);
6081 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6085 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6086 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6087 //It is enforced when constructing a route.
6088 let chanmon_cfgs = create_chanmon_cfgs(2);
6089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6091 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6092 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6094 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6095 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6096 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6097 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6098 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6099 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6100 ), true, APIError::InvalidRoute { ref err },
6101 assert_eq!(err, &"Channel CLTV overflowed?"));
6105 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6106 //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.
6107 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6108 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6109 let chanmon_cfgs = create_chanmon_cfgs(2);
6110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6112 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6113 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6114 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6115 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6117 // Fetch a route in advance as we will be unable to once we're unable to send.
6118 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6119 for i in 0..max_accepted_htlcs {
6120 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6121 let payment_event = {
6122 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6123 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6124 check_added_monitors!(nodes[0], 1);
6126 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6127 assert_eq!(events.len(), 1);
6128 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6129 assert_eq!(htlcs[0].htlc_id, i);
6133 SendEvent::from_event(events.remove(0))
6135 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6136 check_added_monitors!(nodes[1], 0);
6137 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6139 expect_pending_htlcs_forwardable!(nodes[1]);
6140 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6142 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6143 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6144 ), true, APIError::ChannelUnavailable { ref err },
6145 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6147 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6148 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot push more than their max accepted HTLCs", 1);
6152 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6153 //BOLT 2 Requirement: if the sum of total offered HTLCs would exceed the remote's max_htlc_value_in_flight_msat: MUST NOT add an HTLC.
6154 let chanmon_cfgs = create_chanmon_cfgs(2);
6155 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6156 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6157 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6158 let channel_value = 100000;
6159 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6160 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6162 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6164 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6165 // Manually create a route over our max in flight (which our router normally automatically
6167 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6168 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6169 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6170 ), true, APIError::ChannelUnavailable { ref err },
6171 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
6173 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6174 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send value that would put us over the max HTLC value in flight our peer will accept", 1);
6176 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6179 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6181 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6182 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6183 let chanmon_cfgs = create_chanmon_cfgs(2);
6184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6186 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6187 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6188 let htlc_minimum_msat: u64;
6190 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6191 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6192 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6193 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6196 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6197 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6198 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6199 check_added_monitors!(nodes[0], 1);
6200 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6201 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6202 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6203 assert!(nodes[1].node.list_channels().is_empty());
6204 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6205 assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6206 check_added_monitors!(nodes[1], 1);
6207 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6211 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6212 //BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel
6213 let chanmon_cfgs = create_chanmon_cfgs(2);
6214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6216 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6217 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6219 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6220 let channel_reserve = chan_stat.channel_reserve_msat;
6221 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6222 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6223 // The 2* and +1 are for the fee spike reserve.
6224 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6226 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6227 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6228 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6229 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6230 check_added_monitors!(nodes[0], 1);
6231 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6233 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6234 // at this time channel-initiatee receivers are not required to enforce that senders
6235 // respect the fee_spike_reserve.
6236 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6237 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6239 assert!(nodes[1].node.list_channels().is_empty());
6240 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6241 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6242 check_added_monitors!(nodes[1], 1);
6243 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6247 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6248 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6249 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6250 let chanmon_cfgs = create_chanmon_cfgs(2);
6251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6253 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6254 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6256 let send_amt = 3999999;
6257 let (mut route, our_payment_hash, _, our_payment_secret) =
6258 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6259 route.paths[0].hops[0].fee_msat = send_amt;
6260 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6261 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6262 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6263 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6264 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6265 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6267 let mut msg = msgs::UpdateAddHTLC {
6271 payment_hash: our_payment_hash,
6272 cltv_expiry: htlc_cltv,
6273 onion_routing_packet: onion_packet.clone(),
6277 msg.htlc_id = i as u64;
6278 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6280 msg.htlc_id = (50) as u64;
6281 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6283 assert!(nodes[1].node.list_channels().is_empty());
6284 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6285 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6286 check_added_monitors!(nodes[1], 1);
6287 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6291 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6292 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6293 let chanmon_cfgs = create_chanmon_cfgs(2);
6294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6296 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6297 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6299 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6300 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6301 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6302 check_added_monitors!(nodes[0], 1);
6303 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6304 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;
6305 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6307 assert!(nodes[1].node.list_channels().is_empty());
6308 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6309 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6310 check_added_monitors!(nodes[1], 1);
6311 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6315 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6316 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6317 let chanmon_cfgs = create_chanmon_cfgs(2);
6318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6320 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6322 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6323 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6324 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6325 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6326 check_added_monitors!(nodes[0], 1);
6327 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6328 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6329 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6331 assert!(nodes[1].node.list_channels().is_empty());
6332 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6333 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6334 check_added_monitors!(nodes[1], 1);
6335 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6339 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6340 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6341 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6342 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6343 let chanmon_cfgs = create_chanmon_cfgs(2);
6344 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6345 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6346 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6348 create_announced_chan_between_nodes(&nodes, 0, 1);
6349 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6350 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6351 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6352 check_added_monitors!(nodes[0], 1);
6353 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6354 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6356 //Disconnect and Reconnect
6357 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6358 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6359 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
6360 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6361 assert_eq!(reestablish_1.len(), 1);
6362 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
6363 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6364 assert_eq!(reestablish_2.len(), 1);
6365 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6366 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6367 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6368 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6371 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6372 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6373 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6374 check_added_monitors!(nodes[1], 1);
6375 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6379 assert!(nodes[1].node.list_channels().is_empty());
6380 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6381 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6382 check_added_monitors!(nodes[1], 1);
6383 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6387 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6388 //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.
6390 let chanmon_cfgs = create_chanmon_cfgs(2);
6391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6393 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6394 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6395 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6396 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6397 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6399 check_added_monitors!(nodes[0], 1);
6400 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6401 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6403 let update_msg = msgs::UpdateFulfillHTLC{
6406 payment_preimage: our_payment_preimage,
6409 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6411 assert!(nodes[0].node.list_channels().is_empty());
6412 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6413 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()));
6414 check_added_monitors!(nodes[0], 1);
6415 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6419 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6420 //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.
6422 let chanmon_cfgs = create_chanmon_cfgs(2);
6423 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6428 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6429 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6430 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6431 check_added_monitors!(nodes[0], 1);
6432 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6433 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6435 let update_msg = msgs::UpdateFailHTLC{
6438 reason: msgs::OnionErrorPacket { data: Vec::new()},
6441 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6443 assert!(nodes[0].node.list_channels().is_empty());
6444 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6445 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()));
6446 check_added_monitors!(nodes[0], 1);
6447 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6451 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6452 //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.
6454 let chanmon_cfgs = create_chanmon_cfgs(2);
6455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6457 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6458 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6460 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6461 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6462 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6463 check_added_monitors!(nodes[0], 1);
6464 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6465 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6466 let update_msg = msgs::UpdateFailMalformedHTLC{
6469 sha256_of_onion: [1; 32],
6470 failure_code: 0x8000,
6473 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6475 assert!(nodes[0].node.list_channels().is_empty());
6476 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6477 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()));
6478 check_added_monitors!(nodes[0], 1);
6479 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6483 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6484 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6486 let chanmon_cfgs = create_chanmon_cfgs(2);
6487 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6488 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6489 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6490 create_announced_chan_between_nodes(&nodes, 0, 1);
6492 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6494 nodes[1].node.claim_funds(our_payment_preimage);
6495 check_added_monitors!(nodes[1], 1);
6496 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6498 let events = nodes[1].node.get_and_clear_pending_msg_events();
6499 assert_eq!(events.len(), 1);
6500 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6502 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, .. } } => {
6503 assert!(update_add_htlcs.is_empty());
6504 assert_eq!(update_fulfill_htlcs.len(), 1);
6505 assert!(update_fail_htlcs.is_empty());
6506 assert!(update_fail_malformed_htlcs.is_empty());
6507 assert!(update_fee.is_none());
6508 update_fulfill_htlcs[0].clone()
6510 _ => panic!("Unexpected event"),
6514 update_fulfill_msg.htlc_id = 1;
6516 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6518 assert!(nodes[0].node.list_channels().is_empty());
6519 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6520 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6521 check_added_monitors!(nodes[0], 1);
6522 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6526 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6527 //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.
6529 let chanmon_cfgs = create_chanmon_cfgs(2);
6530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6532 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6533 create_announced_chan_between_nodes(&nodes, 0, 1);
6535 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6537 nodes[1].node.claim_funds(our_payment_preimage);
6538 check_added_monitors!(nodes[1], 1);
6539 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6541 let events = nodes[1].node.get_and_clear_pending_msg_events();
6542 assert_eq!(events.len(), 1);
6543 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6545 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, .. } } => {
6546 assert!(update_add_htlcs.is_empty());
6547 assert_eq!(update_fulfill_htlcs.len(), 1);
6548 assert!(update_fail_htlcs.is_empty());
6549 assert!(update_fail_malformed_htlcs.is_empty());
6550 assert!(update_fee.is_none());
6551 update_fulfill_htlcs[0].clone()
6553 _ => panic!("Unexpected event"),
6557 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6559 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6561 assert!(nodes[0].node.list_channels().is_empty());
6562 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6563 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6564 check_added_monitors!(nodes[0], 1);
6565 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6569 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6570 //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.
6572 let chanmon_cfgs = create_chanmon_cfgs(2);
6573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6576 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6578 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6579 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6580 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6581 check_added_monitors!(nodes[0], 1);
6583 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6584 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6586 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6587 check_added_monitors!(nodes[1], 0);
6588 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6590 let events = nodes[1].node.get_and_clear_pending_msg_events();
6592 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6594 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, .. } } => {
6595 assert!(update_add_htlcs.is_empty());
6596 assert!(update_fulfill_htlcs.is_empty());
6597 assert!(update_fail_htlcs.is_empty());
6598 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6599 assert!(update_fee.is_none());
6600 update_fail_malformed_htlcs[0].clone()
6602 _ => panic!("Unexpected event"),
6605 update_msg.failure_code &= !0x8000;
6606 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6608 assert!(nodes[0].node.list_channels().is_empty());
6609 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6610 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6611 check_added_monitors!(nodes[0], 1);
6612 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6616 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6617 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6618 // * 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.
6620 let chanmon_cfgs = create_chanmon_cfgs(3);
6621 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6622 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6623 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6624 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6625 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6627 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6630 let mut payment_event = {
6631 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6632 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6633 check_added_monitors!(nodes[0], 1);
6634 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6635 assert_eq!(events.len(), 1);
6636 SendEvent::from_event(events.remove(0))
6638 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6639 check_added_monitors!(nodes[1], 0);
6640 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6641 expect_pending_htlcs_forwardable!(nodes[1]);
6642 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6643 assert_eq!(events_2.len(), 1);
6644 check_added_monitors!(nodes[1], 1);
6645 payment_event = SendEvent::from_event(events_2.remove(0));
6646 assert_eq!(payment_event.msgs.len(), 1);
6649 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6650 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6651 check_added_monitors!(nodes[2], 0);
6652 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6654 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6655 assert_eq!(events_3.len(), 1);
6656 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6658 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 } } => {
6659 assert!(update_add_htlcs.is_empty());
6660 assert!(update_fulfill_htlcs.is_empty());
6661 assert!(update_fail_htlcs.is_empty());
6662 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6663 assert!(update_fee.is_none());
6664 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6666 _ => panic!("Unexpected event"),
6670 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6672 check_added_monitors!(nodes[1], 0);
6673 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6674 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 }]);
6675 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6676 assert_eq!(events_4.len(), 1);
6678 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6680 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, .. } } => {
6681 assert!(update_add_htlcs.is_empty());
6682 assert!(update_fulfill_htlcs.is_empty());
6683 assert_eq!(update_fail_htlcs.len(), 1);
6684 assert!(update_fail_malformed_htlcs.is_empty());
6685 assert!(update_fee.is_none());
6687 _ => panic!("Unexpected event"),
6690 check_added_monitors!(nodes[1], 1);
6694 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6695 let chanmon_cfgs = create_chanmon_cfgs(3);
6696 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6697 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6698 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6699 create_announced_chan_between_nodes(&nodes, 0, 1);
6700 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6702 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6705 let mut payment_event = {
6706 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6707 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6708 check_added_monitors!(nodes[0], 1);
6709 SendEvent::from_node(&nodes[0])
6712 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6713 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6714 expect_pending_htlcs_forwardable!(nodes[1]);
6715 check_added_monitors!(nodes[1], 1);
6716 payment_event = SendEvent::from_node(&nodes[1]);
6717 assert_eq!(payment_event.msgs.len(), 1);
6720 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6721 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6722 check_added_monitors!(nodes[2], 0);
6723 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6725 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6726 assert_eq!(events_3.len(), 1);
6728 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6729 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6730 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6731 update_msg.failure_code |= 0x2000;
6733 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6734 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6736 _ => panic!("Unexpected event"),
6739 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6740 vec![HTLCDestination::NextHopChannel {
6741 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6742 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6743 assert_eq!(events_4.len(), 1);
6744 check_added_monitors!(nodes[1], 1);
6747 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6748 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6749 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6751 _ => panic!("Unexpected event"),
6754 let events_5 = nodes[0].node.get_and_clear_pending_events();
6755 assert_eq!(events_5.len(), 2);
6757 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6758 // the node originating the error to its next hop.
6760 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6762 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6763 assert!(is_permanent);
6764 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6766 _ => panic!("Unexpected event"),
6769 Event::PaymentFailed { payment_hash, .. } => {
6770 assert_eq!(payment_hash, our_payment_hash);
6772 _ => panic!("Unexpected event"),
6775 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6778 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6779 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6780 // 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
6781 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6783 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6784 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6788 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6790 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6791 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6793 // We route 2 dust-HTLCs between A and B
6794 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6795 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6796 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6798 // Cache one local commitment tx as previous
6799 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6801 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6802 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6803 check_added_monitors!(nodes[1], 0);
6804 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6805 check_added_monitors!(nodes[1], 1);
6807 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6808 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6809 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6810 check_added_monitors!(nodes[0], 1);
6812 // Cache one local commitment tx as lastest
6813 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6815 let events = nodes[0].node.get_and_clear_pending_msg_events();
6817 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6818 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6820 _ => panic!("Unexpected event"),
6823 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6824 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6826 _ => panic!("Unexpected event"),
6829 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6830 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6831 if announce_latest {
6832 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6834 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6837 check_closed_broadcast!(nodes[0], true);
6838 check_added_monitors!(nodes[0], 1);
6839 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6841 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6842 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6843 let events = nodes[0].node.get_and_clear_pending_events();
6844 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6845 assert_eq!(events.len(), 4);
6846 let mut first_failed = false;
6847 for event in events {
6849 Event::PaymentPathFailed { payment_hash, .. } => {
6850 if payment_hash == payment_hash_1 {
6851 assert!(!first_failed);
6852 first_failed = true;
6854 assert_eq!(payment_hash, payment_hash_2);
6857 Event::PaymentFailed { .. } => {}
6858 _ => panic!("Unexpected event"),
6864 fn test_failure_delay_dust_htlc_local_commitment() {
6865 do_test_failure_delay_dust_htlc_local_commitment(true);
6866 do_test_failure_delay_dust_htlc_local_commitment(false);
6869 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6870 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6871 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6872 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6873 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6874 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6875 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6877 let chanmon_cfgs = create_chanmon_cfgs(3);
6878 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6879 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6880 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6881 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6883 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6884 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6886 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6887 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6889 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6890 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6892 // We revoked bs_commitment_tx
6894 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6895 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6898 let mut timeout_tx = Vec::new();
6900 // We fail dust-HTLC 1 by broadcast of local commitment tx
6901 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6902 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6903 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6904 expect_payment_failed!(nodes[0], dust_hash, false);
6906 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6907 check_closed_broadcast!(nodes[0], true);
6908 check_added_monitors!(nodes[0], 1);
6909 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6910 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6911 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6912 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6913 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6914 mine_transaction(&nodes[0], &timeout_tx[0]);
6915 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6916 expect_payment_failed!(nodes[0], non_dust_hash, false);
6918 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6919 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6920 check_closed_broadcast!(nodes[0], true);
6921 check_added_monitors!(nodes[0], 1);
6922 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6923 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6925 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6926 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6927 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6928 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6929 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6930 // dust HTLC should have been failed.
6931 expect_payment_failed!(nodes[0], dust_hash, false);
6934 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6936 assert_eq!(timeout_tx[0].lock_time.0, 11);
6938 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6939 mine_transaction(&nodes[0], &timeout_tx[0]);
6940 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6941 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6942 expect_payment_failed!(nodes[0], non_dust_hash, false);
6947 fn test_sweep_outbound_htlc_failure_update() {
6948 do_test_sweep_outbound_htlc_failure_update(false, true);
6949 do_test_sweep_outbound_htlc_failure_update(false, false);
6950 do_test_sweep_outbound_htlc_failure_update(true, false);
6954 fn test_user_configurable_csv_delay() {
6955 // We test our channel constructors yield errors when we pass them absurd csv delay
6957 let mut low_our_to_self_config = UserConfig::default();
6958 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6959 let mut high_their_to_self_config = UserConfig::default();
6960 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6961 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6962 let chanmon_cfgs = create_chanmon_cfgs(2);
6963 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6964 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6965 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6967 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6968 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6969 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6970 &low_our_to_self_config, 0, 42)
6973 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())); },
6974 _ => panic!("Unexpected event"),
6976 } else { assert!(false) }
6978 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6979 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6980 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6981 open_channel.to_self_delay = 200;
6982 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6983 &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,
6984 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6987 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())); },
6988 _ => panic!("Unexpected event"),
6990 } else { assert!(false); }
6992 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6993 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6994 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()));
6995 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6996 accept_channel.to_self_delay = 200;
6997 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6999 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7001 &ErrorAction::SendErrorMessage { ref msg } => {
7002 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()));
7003 reason_msg = msg.data.clone();
7007 } else { panic!(); }
7008 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7010 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7011 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7012 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7013 open_channel.to_self_delay = 200;
7014 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7015 &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,
7016 &high_their_to_self_config, 0, &nodes[0].logger, 42)
7019 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())); },
7020 _ => panic!("Unexpected event"),
7022 } else { assert!(false); }
7026 fn test_check_htlc_underpaying() {
7027 // Send payment through A -> B but A is maliciously
7028 // sending a probe payment (i.e less than expected value0
7029 // to B, B should refuse payment.
7031 let chanmon_cfgs = create_chanmon_cfgs(2);
7032 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7033 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7034 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7036 // Create some initial channels
7037 create_announced_chan_between_nodes(&nodes, 0, 1);
7039 let scorer = test_utils::TestScorer::new();
7040 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7041 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();
7042 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();
7043 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7044 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7045 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7046 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7047 check_added_monitors!(nodes[0], 1);
7049 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7050 assert_eq!(events.len(), 1);
7051 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7052 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7053 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7055 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7056 // and then will wait a second random delay before failing the HTLC back:
7057 expect_pending_htlcs_forwardable!(nodes[1]);
7058 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7060 // Node 3 is expecting payment of 100_000 but received 10_000,
7061 // it should fail htlc like we didn't know the preimage.
7062 nodes[1].node.process_pending_htlc_forwards();
7064 let events = nodes[1].node.get_and_clear_pending_msg_events();
7065 assert_eq!(events.len(), 1);
7066 let (update_fail_htlc, commitment_signed) = match events[0] {
7067 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 } } => {
7068 assert!(update_add_htlcs.is_empty());
7069 assert!(update_fulfill_htlcs.is_empty());
7070 assert_eq!(update_fail_htlcs.len(), 1);
7071 assert!(update_fail_malformed_htlcs.is_empty());
7072 assert!(update_fee.is_none());
7073 (update_fail_htlcs[0].clone(), commitment_signed)
7075 _ => panic!("Unexpected event"),
7077 check_added_monitors!(nodes[1], 1);
7079 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7080 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7082 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7083 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7084 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7085 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7089 fn test_announce_disable_channels() {
7090 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7091 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7093 let chanmon_cfgs = create_chanmon_cfgs(2);
7094 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7095 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7096 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7098 create_announced_chan_between_nodes(&nodes, 0, 1);
7099 create_announced_chan_between_nodes(&nodes, 1, 0);
7100 create_announced_chan_between_nodes(&nodes, 0, 1);
7103 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7104 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7106 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7107 nodes[0].node.timer_tick_occurred();
7109 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7110 assert_eq!(msg_events.len(), 3);
7111 let mut chans_disabled = HashMap::new();
7112 for e in msg_events {
7114 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7115 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7116 // Check that each channel gets updated exactly once
7117 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7118 panic!("Generated ChannelUpdate for wrong chan!");
7121 _ => panic!("Unexpected event"),
7125 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
7126 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7127 assert_eq!(reestablish_1.len(), 3);
7128 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
7129 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7130 assert_eq!(reestablish_2.len(), 3);
7132 // Reestablish chan_1
7133 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7134 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7135 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7136 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7137 // Reestablish chan_2
7138 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7139 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7140 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7141 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7142 // Reestablish chan_3
7143 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7144 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7145 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7146 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7148 for _ in 0..ENABLE_GOSSIP_TICKS {
7149 nodes[0].node.timer_tick_occurred();
7151 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7152 nodes[0].node.timer_tick_occurred();
7153 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7154 assert_eq!(msg_events.len(), 3);
7155 for e in msg_events {
7157 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7158 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7159 match chans_disabled.remove(&msg.contents.short_channel_id) {
7160 // Each update should have a higher timestamp than the previous one, replacing
7162 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7163 None => panic!("Generated ChannelUpdate for wrong chan!"),
7166 _ => panic!("Unexpected event"),
7169 // Check that each channel gets updated exactly once
7170 assert!(chans_disabled.is_empty());
7174 fn test_bump_penalty_txn_on_revoked_commitment() {
7175 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7176 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7178 let chanmon_cfgs = create_chanmon_cfgs(2);
7179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7181 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7183 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7185 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7186 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7187 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7188 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7189 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7191 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7192 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7193 assert_eq!(revoked_txn[0].output.len(), 4);
7194 assert_eq!(revoked_txn[0].input.len(), 1);
7195 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7196 let revoked_txid = revoked_txn[0].txid();
7198 let mut penalty_sum = 0;
7199 for outp in revoked_txn[0].output.iter() {
7200 if outp.script_pubkey.is_v0_p2wsh() {
7201 penalty_sum += outp.value;
7205 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7206 let header_114 = connect_blocks(&nodes[1], 14);
7208 // Actually revoke tx by claiming a HTLC
7209 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7210 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7211 check_added_monitors!(nodes[1], 1);
7213 // One or more justice tx should have been broadcast, check it
7217 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7218 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7219 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7220 assert_eq!(node_txn[0].output.len(), 1);
7221 check_spends!(node_txn[0], revoked_txn[0]);
7222 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7223 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7224 penalty_1 = node_txn[0].txid();
7228 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7229 connect_blocks(&nodes[1], 15);
7230 let mut penalty_2 = penalty_1;
7231 let mut feerate_2 = 0;
7233 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7234 assert_eq!(node_txn.len(), 1);
7235 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7236 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7237 assert_eq!(node_txn[0].output.len(), 1);
7238 check_spends!(node_txn[0], revoked_txn[0]);
7239 penalty_2 = node_txn[0].txid();
7240 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7241 assert_ne!(penalty_2, penalty_1);
7242 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7243 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7244 // Verify 25% bump heuristic
7245 assert!(feerate_2 * 100 >= feerate_1 * 125);
7249 assert_ne!(feerate_2, 0);
7251 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7252 connect_blocks(&nodes[1], 1);
7254 let mut feerate_3 = 0;
7256 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7257 assert_eq!(node_txn.len(), 1);
7258 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7259 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7260 assert_eq!(node_txn[0].output.len(), 1);
7261 check_spends!(node_txn[0], revoked_txn[0]);
7262 penalty_3 = node_txn[0].txid();
7263 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7264 assert_ne!(penalty_3, penalty_2);
7265 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7266 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7267 // Verify 25% bump heuristic
7268 assert!(feerate_3 * 100 >= feerate_2 * 125);
7272 assert_ne!(feerate_3, 0);
7274 nodes[1].node.get_and_clear_pending_events();
7275 nodes[1].node.get_and_clear_pending_msg_events();
7279 fn test_bump_penalty_txn_on_revoked_htlcs() {
7280 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7281 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7283 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7284 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7287 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7289 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7290 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7291 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7292 let scorer = test_utils::TestScorer::new();
7293 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7294 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7295 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7296 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7297 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7298 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7299 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7300 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7302 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7303 assert_eq!(revoked_local_txn[0].input.len(), 1);
7304 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7306 // Revoke local commitment tx
7307 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7309 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7310 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7311 check_closed_broadcast!(nodes[1], true);
7312 check_added_monitors!(nodes[1], 1);
7313 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7314 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7316 let revoked_htlc_txn = {
7317 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7318 assert_eq!(txn.len(), 2);
7320 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7321 assert_eq!(txn[0].input.len(), 1);
7322 check_spends!(txn[0], revoked_local_txn[0]);
7324 assert_eq!(txn[1].input.len(), 1);
7325 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7326 assert_eq!(txn[1].output.len(), 1);
7327 check_spends!(txn[1], revoked_local_txn[0]);
7332 // Broadcast set of revoked txn on A
7333 let hash_128 = connect_blocks(&nodes[0], 40);
7334 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7335 connect_block(&nodes[0], &block_11);
7336 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7337 connect_block(&nodes[0], &block_129);
7338 let events = nodes[0].node.get_and_clear_pending_events();
7339 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7340 match events.last().unwrap() {
7341 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7342 _ => panic!("Unexpected event"),
7348 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7349 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7350 // Verify claim tx are spending revoked HTLC txn
7352 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7353 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7354 // which are included in the same block (they are broadcasted because we scan the
7355 // transactions linearly and generate claims as we go, they likely should be removed in the
7357 assert_eq!(node_txn[0].input.len(), 1);
7358 check_spends!(node_txn[0], revoked_local_txn[0]);
7359 assert_eq!(node_txn[1].input.len(), 1);
7360 check_spends!(node_txn[1], revoked_local_txn[0]);
7361 assert_eq!(node_txn[2].input.len(), 1);
7362 check_spends!(node_txn[2], revoked_local_txn[0]);
7364 // Each of the three justice transactions claim a separate (single) output of the three
7365 // available, which we check here:
7366 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7367 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7368 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7370 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7371 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7373 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7374 // output, checked above).
7375 assert_eq!(node_txn[3].input.len(), 2);
7376 assert_eq!(node_txn[3].output.len(), 1);
7377 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7379 first = node_txn[3].txid();
7380 // Store both feerates for later comparison
7381 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7382 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7383 penalty_txn = vec![node_txn[2].clone()];
7387 // Connect one more block to see if bumped penalty are issued for HTLC txn
7388 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7389 connect_block(&nodes[0], &block_130);
7390 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7391 connect_block(&nodes[0], &block_131);
7393 // Few more blocks to confirm penalty txn
7394 connect_blocks(&nodes[0], 4);
7395 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7396 let header_144 = connect_blocks(&nodes[0], 9);
7398 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7399 assert_eq!(node_txn.len(), 1);
7401 assert_eq!(node_txn[0].input.len(), 2);
7402 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7403 // Verify bumped tx is different and 25% bump heuristic
7404 assert_ne!(first, node_txn[0].txid());
7405 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7406 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7407 assert!(feerate_2 * 100 > feerate_1 * 125);
7408 let txn = vec![node_txn[0].clone()];
7412 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7413 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7414 connect_blocks(&nodes[0], 20);
7416 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7417 // We verify than no new transaction has been broadcast because previously
7418 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7419 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7420 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7421 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7422 // up bumped justice generation.
7423 assert_eq!(node_txn.len(), 0);
7426 check_closed_broadcast!(nodes[0], true);
7427 check_added_monitors!(nodes[0], 1);
7431 fn test_bump_penalty_txn_on_remote_commitment() {
7432 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7433 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7436 // Provide preimage for one
7437 // Check aggregation
7439 let chanmon_cfgs = create_chanmon_cfgs(2);
7440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7444 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7445 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7446 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7448 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7449 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7450 assert_eq!(remote_txn[0].output.len(), 4);
7451 assert_eq!(remote_txn[0].input.len(), 1);
7452 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7454 // Claim a HTLC without revocation (provide B monitor with preimage)
7455 nodes[1].node.claim_funds(payment_preimage);
7456 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7457 mine_transaction(&nodes[1], &remote_txn[0]);
7458 check_added_monitors!(nodes[1], 2);
7459 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7461 // One or more claim tx should have been broadcast, check it
7465 let feerate_timeout;
7466 let feerate_preimage;
7468 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7469 // 3 transactions including:
7470 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7471 assert_eq!(node_txn.len(), 3);
7472 assert_eq!(node_txn[0].input.len(), 1);
7473 assert_eq!(node_txn[1].input.len(), 1);
7474 assert_eq!(node_txn[2].input.len(), 1);
7475 check_spends!(node_txn[0], remote_txn[0]);
7476 check_spends!(node_txn[1], remote_txn[0]);
7477 check_spends!(node_txn[2], remote_txn[0]);
7479 preimage = node_txn[0].txid();
7480 let index = node_txn[0].input[0].previous_output.vout;
7481 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7482 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7484 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7485 (node_txn[2].clone(), node_txn[1].clone())
7487 (node_txn[1].clone(), node_txn[2].clone())
7490 preimage_bump = preimage_bump_tx;
7491 check_spends!(preimage_bump, remote_txn[0]);
7492 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7494 timeout = timeout_tx.txid();
7495 let index = timeout_tx.input[0].previous_output.vout;
7496 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7497 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7501 assert_ne!(feerate_timeout, 0);
7502 assert_ne!(feerate_preimage, 0);
7504 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7505 connect_blocks(&nodes[1], 1);
7507 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7508 assert_eq!(node_txn.len(), 1);
7509 assert_eq!(node_txn[0].input.len(), 1);
7510 assert_eq!(preimage_bump.input.len(), 1);
7511 check_spends!(node_txn[0], remote_txn[0]);
7512 check_spends!(preimage_bump, remote_txn[0]);
7514 let index = preimage_bump.input[0].previous_output.vout;
7515 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7516 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7517 assert!(new_feerate * 100 > feerate_timeout * 125);
7518 assert_ne!(timeout, preimage_bump.txid());
7520 let index = node_txn[0].input[0].previous_output.vout;
7521 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7522 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7523 assert!(new_feerate * 100 > feerate_preimage * 125);
7524 assert_ne!(preimage, node_txn[0].txid());
7529 nodes[1].node.get_and_clear_pending_events();
7530 nodes[1].node.get_and_clear_pending_msg_events();
7534 fn test_counterparty_raa_skip_no_crash() {
7535 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7536 // commitment transaction, we would have happily carried on and provided them the next
7537 // commitment transaction based on one RAA forward. This would probably eventually have led to
7538 // channel closure, but it would not have resulted in funds loss. Still, our
7539 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7540 // check simply that the channel is closed in response to such an RAA, but don't check whether
7541 // we decide to punish our counterparty for revoking their funds (as we don't currently
7543 let chanmon_cfgs = create_chanmon_cfgs(2);
7544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7546 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7547 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7549 let per_commitment_secret;
7550 let next_per_commitment_point;
7552 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7553 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7554 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7556 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7558 // Make signer believe we got a counterparty signature, so that it allows the revocation
7559 keys.get_enforcement_state().last_holder_commitment -= 1;
7560 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7562 // Must revoke without gaps
7563 keys.get_enforcement_state().last_holder_commitment -= 1;
7564 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7566 keys.get_enforcement_state().last_holder_commitment -= 1;
7567 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7568 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7571 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7572 &msgs::RevokeAndACK {
7574 per_commitment_secret,
7575 next_per_commitment_point,
7577 next_local_nonce: None,
7579 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7580 check_added_monitors!(nodes[1], 1);
7581 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7585 fn test_bump_txn_sanitize_tracking_maps() {
7586 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7587 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7589 let chanmon_cfgs = create_chanmon_cfgs(2);
7590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7592 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7594 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7595 // Lock HTLC in both directions
7596 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7597 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7599 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7600 assert_eq!(revoked_local_txn[0].input.len(), 1);
7601 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7603 // Revoke local commitment tx
7604 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7606 // Broadcast set of revoked txn on A
7607 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7608 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7609 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7611 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7612 check_closed_broadcast!(nodes[0], true);
7613 check_added_monitors!(nodes[0], 1);
7614 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7616 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7617 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7618 check_spends!(node_txn[0], revoked_local_txn[0]);
7619 check_spends!(node_txn[1], revoked_local_txn[0]);
7620 check_spends!(node_txn[2], revoked_local_txn[0]);
7621 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7625 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7626 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7628 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7629 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7630 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7635 fn test_channel_conf_timeout() {
7636 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7637 // confirm within 2016 blocks, as recommended by BOLT 2.
7638 let chanmon_cfgs = create_chanmon_cfgs(2);
7639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7643 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7645 // The outbound node should wait forever for confirmation:
7646 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7647 // copied here instead of directly referencing the constant.
7648 connect_blocks(&nodes[0], 2016);
7649 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7651 // The inbound node should fail the channel after exactly 2016 blocks
7652 connect_blocks(&nodes[1], 2015);
7653 check_added_monitors!(nodes[1], 0);
7654 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7656 connect_blocks(&nodes[1], 1);
7657 check_added_monitors!(nodes[1], 1);
7658 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7659 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7660 assert_eq!(close_ev.len(), 1);
7662 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7663 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7664 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7666 _ => panic!("Unexpected event"),
7671 fn test_override_channel_config() {
7672 let chanmon_cfgs = create_chanmon_cfgs(2);
7673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7675 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7677 // Node0 initiates a channel to node1 using the override config.
7678 let mut override_config = UserConfig::default();
7679 override_config.channel_handshake_config.our_to_self_delay = 200;
7681 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7683 // Assert the channel created by node0 is using the override config.
7684 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7685 assert_eq!(res.channel_flags, 0);
7686 assert_eq!(res.to_self_delay, 200);
7690 fn test_override_0msat_htlc_minimum() {
7691 let mut zero_config = UserConfig::default();
7692 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7693 let chanmon_cfgs = create_chanmon_cfgs(2);
7694 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7695 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7696 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7698 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7699 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7700 assert_eq!(res.htlc_minimum_msat, 1);
7702 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7703 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7704 assert_eq!(res.htlc_minimum_msat, 1);
7708 fn test_channel_update_has_correct_htlc_maximum_msat() {
7709 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7710 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7711 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7712 // 90% of the `channel_value`.
7713 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7715 let mut config_30_percent = UserConfig::default();
7716 config_30_percent.channel_handshake_config.announced_channel = true;
7717 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7718 let mut config_50_percent = UserConfig::default();
7719 config_50_percent.channel_handshake_config.announced_channel = true;
7720 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7721 let mut config_95_percent = UserConfig::default();
7722 config_95_percent.channel_handshake_config.announced_channel = true;
7723 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7724 let mut config_100_percent = UserConfig::default();
7725 config_100_percent.channel_handshake_config.announced_channel = true;
7726 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7728 let chanmon_cfgs = create_chanmon_cfgs(4);
7729 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7730 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)]);
7731 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7733 let channel_value_satoshis = 100000;
7734 let channel_value_msat = channel_value_satoshis * 1000;
7735 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7736 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7737 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7739 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7740 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7742 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7743 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7744 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7745 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7746 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7747 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7749 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7750 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7752 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7753 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7754 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7756 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7760 fn test_manually_accept_inbound_channel_request() {
7761 let mut manually_accept_conf = UserConfig::default();
7762 manually_accept_conf.manually_accept_inbound_channels = true;
7763 let chanmon_cfgs = create_chanmon_cfgs(2);
7764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7766 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7768 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7769 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7771 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7773 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7774 // accepting the inbound channel request.
7775 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7777 let events = nodes[1].node.get_and_clear_pending_events();
7779 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7780 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7782 _ => panic!("Unexpected event"),
7785 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7786 assert_eq!(accept_msg_ev.len(), 1);
7788 match accept_msg_ev[0] {
7789 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7790 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7792 _ => panic!("Unexpected event"),
7795 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7797 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7798 assert_eq!(close_msg_ev.len(), 1);
7800 let events = nodes[1].node.get_and_clear_pending_events();
7802 Event::ChannelClosed { user_channel_id, .. } => {
7803 assert_eq!(user_channel_id, 23);
7805 _ => panic!("Unexpected event"),
7810 fn test_manually_reject_inbound_channel_request() {
7811 let mut manually_accept_conf = UserConfig::default();
7812 manually_accept_conf.manually_accept_inbound_channels = true;
7813 let chanmon_cfgs = create_chanmon_cfgs(2);
7814 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7815 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7816 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7818 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7819 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7821 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7823 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7824 // rejecting the inbound channel request.
7825 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7827 let events = nodes[1].node.get_and_clear_pending_events();
7829 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7830 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7832 _ => panic!("Unexpected event"),
7835 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7836 assert_eq!(close_msg_ev.len(), 1);
7838 match close_msg_ev[0] {
7839 MessageSendEvent::HandleError { ref node_id, .. } => {
7840 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7842 _ => panic!("Unexpected event"),
7844 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7848 fn test_reject_funding_before_inbound_channel_accepted() {
7849 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7850 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7851 // the node operator before the counterparty sends a `FundingCreated` message. If a
7852 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7853 // and the channel should be closed.
7854 let mut manually_accept_conf = UserConfig::default();
7855 manually_accept_conf.manually_accept_inbound_channels = true;
7856 let chanmon_cfgs = create_chanmon_cfgs(2);
7857 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7858 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7859 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7861 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7862 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7863 let temp_channel_id = res.temporary_channel_id;
7865 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7867 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7868 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7870 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7871 nodes[1].node.get_and_clear_pending_events();
7873 // Get the `AcceptChannel` message of `nodes[1]` without calling
7874 // `ChannelManager::accept_inbound_channel`, which generates a
7875 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7876 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7877 // succeed when `nodes[0]` is passed to it.
7878 let accept_chan_msg = {
7879 let mut node_1_per_peer_lock;
7880 let mut node_1_peer_state_lock;
7881 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7882 channel.get_accept_channel_message()
7884 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7886 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7888 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7889 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7891 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7892 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7894 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7895 assert_eq!(close_msg_ev.len(), 1);
7897 let expected_err = "FundingCreated message received before the channel was accepted";
7898 match close_msg_ev[0] {
7899 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7900 assert_eq!(msg.channel_id, temp_channel_id);
7901 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7902 assert_eq!(msg.data, expected_err);
7904 _ => panic!("Unexpected event"),
7907 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7911 fn test_can_not_accept_inbound_channel_twice() {
7912 let mut manually_accept_conf = UserConfig::default();
7913 manually_accept_conf.manually_accept_inbound_channels = true;
7914 let chanmon_cfgs = create_chanmon_cfgs(2);
7915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7917 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7919 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7920 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7922 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7924 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7925 // accepting the inbound channel request.
7926 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7928 let events = nodes[1].node.get_and_clear_pending_events();
7930 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7931 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7932 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7934 Err(APIError::APIMisuseError { err }) => {
7935 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7937 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7938 Err(_) => panic!("Unexpected Error"),
7941 _ => panic!("Unexpected event"),
7944 // Ensure that the channel wasn't closed after attempting to accept it twice.
7945 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7946 assert_eq!(accept_msg_ev.len(), 1);
7948 match accept_msg_ev[0] {
7949 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7950 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7952 _ => panic!("Unexpected event"),
7957 fn test_can_not_accept_unknown_inbound_channel() {
7958 let chanmon_cfg = create_chanmon_cfgs(2);
7959 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7960 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7961 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7963 let unknown_channel_id = [0; 32];
7964 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7966 Err(APIError::ChannelUnavailable { err }) => {
7967 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()));
7969 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7970 Err(_) => panic!("Unexpected Error"),
7975 fn test_onion_value_mpp_set_calculation() {
7976 // Test that we use the onion value `amt_to_forward` when
7977 // calculating whether we've reached the `total_msat` of an MPP
7978 // by having a routing node forward more than `amt_to_forward`
7979 // and checking that the receiving node doesn't generate
7980 // a PaymentClaimable event too early
7982 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7983 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7984 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7985 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7987 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7988 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7989 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7990 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7992 let total_msat = 100_000;
7993 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7994 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7995 let sample_path = route.paths.pop().unwrap();
7997 let mut path_1 = sample_path.clone();
7998 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7999 path_1.hops[0].short_channel_id = chan_1_id;
8000 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8001 path_1.hops[1].short_channel_id = chan_3_id;
8002 path_1.hops[1].fee_msat = 100_000;
8003 route.paths.push(path_1);
8005 let mut path_2 = sample_path.clone();
8006 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8007 path_2.hops[0].short_channel_id = chan_2_id;
8008 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8009 path_2.hops[1].short_channel_id = chan_4_id;
8010 path_2.hops[1].fee_msat = 1_000;
8011 route.paths.push(path_2);
8014 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8015 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8016 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8017 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8018 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8019 check_added_monitors!(nodes[0], expected_paths.len());
8021 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8022 assert_eq!(events.len(), expected_paths.len());
8025 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8026 let mut payment_event = SendEvent::from_event(ev);
8027 let mut prev_node = &nodes[0];
8029 for (idx, &node) in expected_paths[0].iter().enumerate() {
8030 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8032 if idx == 0 { // routing node
8033 let session_priv = [3; 32];
8034 let height = nodes[0].best_block_info().1;
8035 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8036 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8037 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8038 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8039 // Edit amt_to_forward to simulate the sender having set
8040 // the final amount and the routing node taking less fee
8041 onion_payloads[1].amt_to_forward = 99_000;
8042 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8043 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8046 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8047 check_added_monitors!(node, 0);
8048 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8049 expect_pending_htlcs_forwardable!(node);
8052 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8053 assert_eq!(events_2.len(), 1);
8054 check_added_monitors!(node, 1);
8055 payment_event = SendEvent::from_event(events_2.remove(0));
8056 assert_eq!(payment_event.msgs.len(), 1);
8058 let events_2 = node.node.get_and_clear_pending_events();
8059 assert!(events_2.is_empty());
8066 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8067 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8069 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8072 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8074 let routing_node_count = msat_amounts.len();
8075 let node_count = routing_node_count + 2;
8077 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8078 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8079 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8080 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8085 // Create channels for each amount
8086 let mut expected_paths = Vec::with_capacity(routing_node_count);
8087 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8088 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8089 for i in 0..routing_node_count {
8090 let routing_node = 2 + i;
8091 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8092 src_chan_ids.push(src_chan_id);
8093 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8094 dst_chan_ids.push(dst_chan_id);
8095 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8096 expected_paths.push(path);
8098 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8100 // Create a route for each amount
8101 let example_amount = 100000;
8102 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);
8103 let sample_path = route.paths.pop().unwrap();
8104 for i in 0..routing_node_count {
8105 let routing_node = 2 + i;
8106 let mut path = sample_path.clone();
8107 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8108 path.hops[0].short_channel_id = src_chan_ids[i];
8109 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8110 path.hops[1].short_channel_id = dst_chan_ids[i];
8111 path.hops[1].fee_msat = msat_amounts[i];
8112 route.paths.push(path);
8115 // Send payment with manually set total_msat
8116 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8117 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8118 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8119 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8120 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8121 check_added_monitors!(nodes[src_idx], expected_paths.len());
8123 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8124 assert_eq!(events.len(), expected_paths.len());
8125 let mut amount_received = 0;
8126 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8127 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8129 let current_path_amount = msat_amounts[path_idx];
8130 amount_received += current_path_amount;
8131 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8132 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8135 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8139 fn test_overshoot_mpp() {
8140 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8141 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8145 fn test_simple_mpp() {
8146 // Simple test of sending a multi-path payment.
8147 let chanmon_cfgs = create_chanmon_cfgs(4);
8148 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8149 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8150 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8152 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8153 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8154 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8155 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8157 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8158 let path = route.paths[0].clone();
8159 route.paths.push(path);
8160 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8161 route.paths[0].hops[0].short_channel_id = chan_1_id;
8162 route.paths[0].hops[1].short_channel_id = chan_3_id;
8163 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8164 route.paths[1].hops[0].short_channel_id = chan_2_id;
8165 route.paths[1].hops[1].short_channel_id = chan_4_id;
8166 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8167 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8171 fn test_preimage_storage() {
8172 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8173 let chanmon_cfgs = create_chanmon_cfgs(2);
8174 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8175 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8176 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8178 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8181 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8182 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8183 nodes[0].node.send_payment_with_route(&route, payment_hash,
8184 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8185 check_added_monitors!(nodes[0], 1);
8186 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8187 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8188 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8189 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8191 // Note that after leaving the above scope we have no knowledge of any arguments or return
8192 // values from previous calls.
8193 expect_pending_htlcs_forwardable!(nodes[1]);
8194 let events = nodes[1].node.get_and_clear_pending_events();
8195 assert_eq!(events.len(), 1);
8197 Event::PaymentClaimable { ref purpose, .. } => {
8199 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8200 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8202 _ => panic!("expected PaymentPurpose::InvoicePayment")
8205 _ => panic!("Unexpected event"),
8210 #[allow(deprecated)]
8211 fn test_secret_timeout() {
8212 // Simple test of payment secret storage time outs. After
8213 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8214 let chanmon_cfgs = create_chanmon_cfgs(2);
8215 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8216 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8217 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8219 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8221 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8223 // We should fail to register the same payment hash twice, at least until we've connected a
8224 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8225 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8226 assert_eq!(err, "Duplicate payment hash");
8227 } else { panic!(); }
8229 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8230 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8232 connect_block(&nodes[1], &block);
8233 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8234 assert_eq!(err, "Duplicate payment hash");
8235 } else { panic!(); }
8237 // If we then connect the second block, we should be able to register the same payment hash
8238 // again (this time getting a new payment secret).
8239 block.header.prev_blockhash = block.header.block_hash();
8240 block.header.time += 1;
8241 connect_block(&nodes[1], &block);
8242 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8243 assert_ne!(payment_secret_1, our_payment_secret);
8246 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8247 nodes[0].node.send_payment_with_route(&route, payment_hash,
8248 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8249 check_added_monitors!(nodes[0], 1);
8250 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8251 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8252 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8253 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8255 // Note that after leaving the above scope we have no knowledge of any arguments or return
8256 // values from previous calls.
8257 expect_pending_htlcs_forwardable!(nodes[1]);
8258 let events = nodes[1].node.get_and_clear_pending_events();
8259 assert_eq!(events.len(), 1);
8261 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8262 assert!(payment_preimage.is_none());
8263 assert_eq!(payment_secret, our_payment_secret);
8264 // We don't actually have the payment preimage with which to claim this payment!
8266 _ => panic!("Unexpected event"),
8271 fn test_bad_secret_hash() {
8272 // Simple test of unregistered payment hash/invalid payment secret handling
8273 let chanmon_cfgs = create_chanmon_cfgs(2);
8274 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8275 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8276 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8278 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8280 let random_payment_hash = PaymentHash([42; 32]);
8281 let random_payment_secret = PaymentSecret([43; 32]);
8282 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8283 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8285 // All the below cases should end up being handled exactly identically, so we macro the
8286 // resulting events.
8287 macro_rules! handle_unknown_invalid_payment_data {
8288 ($payment_hash: expr) => {
8289 check_added_monitors!(nodes[0], 1);
8290 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8291 let payment_event = SendEvent::from_event(events.pop().unwrap());
8292 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8293 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8295 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8296 // again to process the pending backwards-failure of the HTLC
8297 expect_pending_htlcs_forwardable!(nodes[1]);
8298 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8299 check_added_monitors!(nodes[1], 1);
8301 // We should fail the payment back
8302 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8303 match events.pop().unwrap() {
8304 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8305 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8306 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8308 _ => panic!("Unexpected event"),
8313 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8314 // Error data is the HTLC value (100,000) and current block height
8315 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8317 // Send a payment with the right payment hash but the wrong payment secret
8318 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8319 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8320 handle_unknown_invalid_payment_data!(our_payment_hash);
8321 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8323 // Send a payment with a random payment hash, but the right payment secret
8324 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8325 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8326 handle_unknown_invalid_payment_data!(random_payment_hash);
8327 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8329 // Send a payment with a random payment hash and random payment secret
8330 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8331 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8332 handle_unknown_invalid_payment_data!(random_payment_hash);
8333 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8337 fn test_update_err_monitor_lockdown() {
8338 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8339 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8340 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8343 // This scenario may happen in a watchtower setup, where watchtower process a block height
8344 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8345 // commitment at same time.
8347 let chanmon_cfgs = create_chanmon_cfgs(2);
8348 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8349 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8350 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8352 // Create some initial channel
8353 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8354 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8356 // Rebalance the network to generate htlc in the two directions
8357 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8359 // Route a HTLC from node 0 to node 1 (but don't settle)
8360 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8362 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8363 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8364 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8365 let persister = test_utils::TestPersister::new();
8368 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8369 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8370 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8371 assert!(new_monitor == *monitor);
8374 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);
8375 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8378 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8379 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8380 // transaction lock time requirements here.
8381 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8382 watchtower.chain_monitor.block_connected(&block, 200);
8384 // Try to update ChannelMonitor
8385 nodes[1].node.claim_funds(preimage);
8386 check_added_monitors!(nodes[1], 1);
8387 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8389 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8390 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8391 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8393 let mut node_0_per_peer_lock;
8394 let mut node_0_peer_state_lock;
8395 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8396 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8397 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8398 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8399 } else { assert!(false); }
8401 // Our local monitor is in-sync and hasn't processed yet timeout
8402 check_added_monitors!(nodes[0], 1);
8403 let events = nodes[0].node.get_and_clear_pending_events();
8404 assert_eq!(events.len(), 1);
8408 fn test_concurrent_monitor_claim() {
8409 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8410 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8411 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8412 // state N+1 confirms. Alice claims output from state N+1.
8414 let chanmon_cfgs = create_chanmon_cfgs(2);
8415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8417 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8419 // Create some initial channel
8420 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8421 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8423 // Rebalance the network to generate htlc in the two directions
8424 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8426 // Route a HTLC from node 0 to node 1 (but don't settle)
8427 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8429 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8430 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8431 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8432 let persister = test_utils::TestPersister::new();
8433 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8434 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8436 let watchtower_alice = {
8438 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8439 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8440 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8441 assert!(new_monitor == *monitor);
8444 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8445 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8448 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8449 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8450 // requirements here.
8451 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8452 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8453 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8455 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8457 let mut txn = alice_broadcaster.txn_broadcast();
8458 assert_eq!(txn.len(), 2);
8462 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8463 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8464 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8465 let persister = test_utils::TestPersister::new();
8466 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8467 let watchtower_bob = {
8469 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8470 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8471 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8472 assert!(new_monitor == *monitor);
8475 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8476 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8479 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8481 // Route another payment to generate another update with still previous HTLC pending
8482 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8483 nodes[1].node.send_payment_with_route(&route, payment_hash,
8484 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8485 check_added_monitors!(nodes[1], 1);
8487 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8488 assert_eq!(updates.update_add_htlcs.len(), 1);
8489 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8491 let mut node_0_per_peer_lock;
8492 let mut node_0_peer_state_lock;
8493 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8494 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8495 // Watchtower Alice should already have seen the block and reject the update
8496 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8497 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8498 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8499 } else { assert!(false); }
8501 // Our local monitor is in-sync and hasn't processed yet timeout
8502 check_added_monitors!(nodes[0], 1);
8504 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8505 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8507 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8510 let mut txn = bob_broadcaster.txn_broadcast();
8511 assert_eq!(txn.len(), 2);
8512 bob_state_y = txn.remove(0);
8515 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8516 let height = HTLC_TIMEOUT_BROADCAST + 1;
8517 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8518 check_closed_broadcast(&nodes[0], 1, true);
8519 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8520 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8521 check_added_monitors(&nodes[0], 1);
8523 let htlc_txn = alice_broadcaster.txn_broadcast();
8524 assert_eq!(htlc_txn.len(), 2);
8525 check_spends!(htlc_txn[0], bob_state_y);
8526 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8527 // it. However, she should, because it now has an invalid parent.
8528 check_spends!(htlc_txn[1], alice_state);
8533 fn test_pre_lockin_no_chan_closed_update() {
8534 // Test that if a peer closes a channel in response to a funding_created message we don't
8535 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8538 // Doing so would imply a channel monitor update before the initial channel monitor
8539 // registration, violating our API guarantees.
8541 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8542 // then opening a second channel with the same funding output as the first (which is not
8543 // rejected because the first channel does not exist in the ChannelManager) and closing it
8544 // before receiving funding_signed.
8545 let chanmon_cfgs = create_chanmon_cfgs(2);
8546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8548 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8550 // Create an initial channel
8551 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8552 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8553 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8554 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8555 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8557 // Move the first channel through the funding flow...
8558 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8560 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8561 check_added_monitors!(nodes[0], 0);
8563 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8564 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8565 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8566 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8567 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8571 fn test_htlc_no_detection() {
8572 // This test is a mutation to underscore the detection logic bug we had
8573 // before #653. HTLC value routed is above the remaining balance, thus
8574 // inverting HTLC and `to_remote` output. HTLC will come second and
8575 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8576 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8577 // outputs order detection for correct spending children filtring.
8579 let chanmon_cfgs = create_chanmon_cfgs(2);
8580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8582 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8584 // Create some initial channels
8585 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8587 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8588 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8589 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8590 assert_eq!(local_txn[0].input.len(), 1);
8591 assert_eq!(local_txn[0].output.len(), 3);
8592 check_spends!(local_txn[0], chan_1.3);
8594 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8595 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8596 connect_block(&nodes[0], &block);
8597 // We deliberately connect the local tx twice as this should provoke a failure calling
8598 // this test before #653 fix.
8599 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8600 check_closed_broadcast!(nodes[0], true);
8601 check_added_monitors!(nodes[0], 1);
8602 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8603 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8605 let htlc_timeout = {
8606 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8607 assert_eq!(node_txn.len(), 1);
8608 assert_eq!(node_txn[0].input.len(), 1);
8609 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8610 check_spends!(node_txn[0], local_txn[0]);
8614 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8615 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8616 expect_payment_failed!(nodes[0], our_payment_hash, false);
8619 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8620 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8621 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8622 // Carol, Alice would be the upstream node, and Carol the downstream.)
8624 // Steps of the test:
8625 // 1) Alice sends a HTLC to Carol through Bob.
8626 // 2) Carol doesn't settle the HTLC.
8627 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8628 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8629 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8630 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8631 // 5) Carol release the preimage to Bob off-chain.
8632 // 6) Bob claims the offered output on the broadcasted commitment.
8633 let chanmon_cfgs = create_chanmon_cfgs(3);
8634 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8635 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8636 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8638 // Create some initial channels
8639 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8640 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8642 // Steps (1) and (2):
8643 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8644 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8646 // Check that Alice's commitment transaction now contains an output for this HTLC.
8647 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8648 check_spends!(alice_txn[0], chan_ab.3);
8649 assert_eq!(alice_txn[0].output.len(), 2);
8650 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8651 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8652 assert_eq!(alice_txn.len(), 2);
8654 // Steps (3) and (4):
8655 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8656 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8657 let mut force_closing_node = 0; // Alice force-closes
8658 let mut counterparty_node = 1; // Bob if Alice force-closes
8661 if !broadcast_alice {
8662 force_closing_node = 1;
8663 counterparty_node = 0;
8665 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8666 check_closed_broadcast!(nodes[force_closing_node], true);
8667 check_added_monitors!(nodes[force_closing_node], 1);
8668 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8669 if go_onchain_before_fulfill {
8670 let txn_to_broadcast = match broadcast_alice {
8671 true => alice_txn.clone(),
8672 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8674 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8675 if broadcast_alice {
8676 check_closed_broadcast!(nodes[1], true);
8677 check_added_monitors!(nodes[1], 1);
8678 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8683 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8684 // process of removing the HTLC from their commitment transactions.
8685 nodes[2].node.claim_funds(payment_preimage);
8686 check_added_monitors!(nodes[2], 1);
8687 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8689 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8690 assert!(carol_updates.update_add_htlcs.is_empty());
8691 assert!(carol_updates.update_fail_htlcs.is_empty());
8692 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8693 assert!(carol_updates.update_fee.is_none());
8694 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8696 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8697 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8698 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8699 if !go_onchain_before_fulfill && broadcast_alice {
8700 let events = nodes[1].node.get_and_clear_pending_msg_events();
8701 assert_eq!(events.len(), 1);
8703 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8704 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8706 _ => panic!("Unexpected event"),
8709 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8710 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8711 // Carol<->Bob's updated commitment transaction info.
8712 check_added_monitors!(nodes[1], 2);
8714 let events = nodes[1].node.get_and_clear_pending_msg_events();
8715 assert_eq!(events.len(), 2);
8716 let bob_revocation = match events[0] {
8717 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8718 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8721 _ => panic!("Unexpected event"),
8723 let bob_updates = match events[1] {
8724 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8725 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8728 _ => panic!("Unexpected event"),
8731 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8732 check_added_monitors!(nodes[2], 1);
8733 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8734 check_added_monitors!(nodes[2], 1);
8736 let events = nodes[2].node.get_and_clear_pending_msg_events();
8737 assert_eq!(events.len(), 1);
8738 let carol_revocation = match events[0] {
8739 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8740 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8743 _ => panic!("Unexpected event"),
8745 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8746 check_added_monitors!(nodes[1], 1);
8748 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8749 // here's where we put said channel's commitment tx on-chain.
8750 let mut txn_to_broadcast = alice_txn.clone();
8751 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8752 if !go_onchain_before_fulfill {
8753 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8754 // If Bob was the one to force-close, he will have already passed these checks earlier.
8755 if broadcast_alice {
8756 check_closed_broadcast!(nodes[1], true);
8757 check_added_monitors!(nodes[1], 1);
8758 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8760 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8761 if broadcast_alice {
8762 assert_eq!(bob_txn.len(), 1);
8763 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8765 assert_eq!(bob_txn.len(), 2);
8766 check_spends!(bob_txn[0], chan_ab.3);
8771 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8772 // broadcasted commitment transaction.
8774 let script_weight = match broadcast_alice {
8775 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8776 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8778 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8779 // Bob force-closed and broadcasts the commitment transaction along with a
8780 // HTLC-output-claiming transaction.
8781 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8782 if broadcast_alice {
8783 assert_eq!(bob_txn.len(), 1);
8784 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8785 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8787 assert_eq!(bob_txn.len(), 2);
8788 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8789 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8795 fn test_onchain_htlc_settlement_after_close() {
8796 do_test_onchain_htlc_settlement_after_close(true, true);
8797 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8798 do_test_onchain_htlc_settlement_after_close(true, false);
8799 do_test_onchain_htlc_settlement_after_close(false, false);
8803 fn test_duplicate_temporary_channel_id_from_different_peers() {
8804 // Tests that we can accept two different `OpenChannel` requests with the same
8805 // `temporary_channel_id`, as long as they are from different peers.
8806 let chanmon_cfgs = create_chanmon_cfgs(3);
8807 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8808 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8809 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8811 // Create an first channel channel
8812 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8813 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8815 // Create an second channel
8816 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8817 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8819 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8820 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8821 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8823 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8824 // `temporary_channel_id` as they are from different peers.
8825 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8827 let events = nodes[0].node.get_and_clear_pending_msg_events();
8828 assert_eq!(events.len(), 1);
8830 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8831 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8832 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8834 _ => panic!("Unexpected event"),
8838 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8840 let events = nodes[0].node.get_and_clear_pending_msg_events();
8841 assert_eq!(events.len(), 1);
8843 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8844 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8845 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8847 _ => panic!("Unexpected event"),
8853 fn test_duplicate_chan_id() {
8854 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8855 // already open we reject it and keep the old channel.
8857 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8858 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8859 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8860 // updating logic for the existing channel.
8861 let chanmon_cfgs = create_chanmon_cfgs(2);
8862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8864 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8866 // Create an initial channel
8867 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8868 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8869 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8870 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()));
8872 // Try to create a second channel with the same temporary_channel_id as the first and check
8873 // that it is rejected.
8874 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8876 let events = nodes[1].node.get_and_clear_pending_msg_events();
8877 assert_eq!(events.len(), 1);
8879 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8880 // Technically, at this point, nodes[1] would be justified in thinking both the
8881 // first (valid) and second (invalid) channels are closed, given they both have
8882 // the same non-temporary channel_id. However, currently we do not, so we just
8883 // move forward with it.
8884 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8885 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8887 _ => panic!("Unexpected event"),
8891 // Move the first channel through the funding flow...
8892 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8894 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8895 check_added_monitors!(nodes[0], 0);
8897 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8898 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8900 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8901 assert_eq!(added_monitors.len(), 1);
8902 assert_eq!(added_monitors[0].0, funding_output);
8903 added_monitors.clear();
8905 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8907 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8909 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8910 let channel_id = funding_outpoint.to_channel_id();
8912 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8915 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8916 // Technically this is allowed by the spec, but we don't support it and there's little reason
8917 // to. Still, it shouldn't cause any other issues.
8918 open_chan_msg.temporary_channel_id = channel_id;
8919 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8921 let events = nodes[1].node.get_and_clear_pending_msg_events();
8922 assert_eq!(events.len(), 1);
8924 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8925 // Technically, at this point, nodes[1] would be justified in thinking both
8926 // channels are closed, but currently we do not, so we just move forward with it.
8927 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8928 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8930 _ => panic!("Unexpected event"),
8934 // Now try to create a second channel which has a duplicate funding output.
8935 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8936 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8937 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8938 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()));
8939 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8941 let funding_created = {
8942 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8943 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8944 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8945 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8946 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8947 // channelmanager in a possibly nonsense state instead).
8948 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8949 let logger = test_utils::TestLogger::new();
8950 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8952 check_added_monitors!(nodes[0], 0);
8953 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8954 // At this point we'll look up if the channel_id is present and immediately fail the channel
8955 // without trying to persist the `ChannelMonitor`.
8956 check_added_monitors!(nodes[1], 0);
8958 // ...still, nodes[1] will reject the duplicate channel.
8960 let events = nodes[1].node.get_and_clear_pending_msg_events();
8961 assert_eq!(events.len(), 1);
8963 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8964 // Technically, at this point, nodes[1] would be justified in thinking both
8965 // channels are closed, but currently we do not, so we just move forward with it.
8966 assert_eq!(msg.channel_id, channel_id);
8967 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8969 _ => panic!("Unexpected event"),
8973 // finally, finish creating the original channel and send a payment over it to make sure
8974 // everything is functional.
8975 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8977 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8978 assert_eq!(added_monitors.len(), 1);
8979 assert_eq!(added_monitors[0].0, funding_output);
8980 added_monitors.clear();
8982 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8984 let events_4 = nodes[0].node.get_and_clear_pending_events();
8985 assert_eq!(events_4.len(), 0);
8986 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8987 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8989 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8990 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8991 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8993 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8997 fn test_error_chans_closed() {
8998 // Test that we properly handle error messages, closing appropriate channels.
9000 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9001 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9002 // we can test various edge cases around it to ensure we don't regress.
9003 let chanmon_cfgs = create_chanmon_cfgs(3);
9004 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9005 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9006 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9008 // Create some initial channels
9009 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9010 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9011 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9013 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9014 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9015 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9017 // Closing a channel from a different peer has no effect
9018 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9019 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9021 // Closing one channel doesn't impact others
9022 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9023 check_added_monitors!(nodes[0], 1);
9024 check_closed_broadcast!(nodes[0], false);
9025 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9026 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9027 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9028 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);
9029 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);
9031 // A null channel ID should close all channels
9032 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9033 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9034 check_added_monitors!(nodes[0], 2);
9035 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9036 let events = nodes[0].node.get_and_clear_pending_msg_events();
9037 assert_eq!(events.len(), 2);
9039 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9040 assert_eq!(msg.contents.flags & 2, 2);
9042 _ => panic!("Unexpected event"),
9045 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9046 assert_eq!(msg.contents.flags & 2, 2);
9048 _ => panic!("Unexpected event"),
9050 // Note that at this point users of a standard PeerHandler will end up calling
9051 // peer_disconnected.
9052 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9053 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9055 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9056 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9057 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9061 fn test_invalid_funding_tx() {
9062 // Test that we properly handle invalid funding transactions sent to us from a peer.
9064 // Previously, all other major lightning implementations had failed to properly sanitize
9065 // funding transactions from their counterparties, leading to a multi-implementation critical
9066 // security vulnerability (though we always sanitized properly, we've previously had
9067 // un-released crashes in the sanitization process).
9069 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9070 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9071 // gave up on it. We test this here by generating such a transaction.
9072 let chanmon_cfgs = create_chanmon_cfgs(2);
9073 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9074 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9075 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9077 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9078 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()));
9079 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()));
9081 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9083 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9084 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9085 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9087 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9088 let wit_program_script: Script = wit_program.into();
9089 for output in tx.output.iter_mut() {
9090 // Make the confirmed funding transaction have a bogus script_pubkey
9091 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9094 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9095 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()));
9096 check_added_monitors!(nodes[1], 1);
9097 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9099 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()));
9100 check_added_monitors!(nodes[0], 1);
9101 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9103 let events_1 = nodes[0].node.get_and_clear_pending_events();
9104 assert_eq!(events_1.len(), 0);
9106 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9107 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9108 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9110 let expected_err = "funding tx had wrong script/value or output index";
9111 confirm_transaction_at(&nodes[1], &tx, 1);
9112 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9113 check_added_monitors!(nodes[1], 1);
9114 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9115 assert_eq!(events_2.len(), 1);
9116 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9117 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9118 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9119 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9120 } else { panic!(); }
9121 } else { panic!(); }
9122 assert_eq!(nodes[1].node.list_channels().len(), 0);
9124 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9125 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9126 // as its not 32 bytes long.
9127 let mut spend_tx = Transaction {
9128 version: 2i32, lock_time: PackedLockTime::ZERO,
9129 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9130 previous_output: BitcoinOutPoint {
9134 script_sig: Script::new(),
9135 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9136 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9138 output: vec![TxOut {
9140 script_pubkey: Script::new(),
9143 check_spends!(spend_tx, tx);
9144 mine_transaction(&nodes[1], &spend_tx);
9147 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9148 // In the first version of the chain::Confirm interface, after a refactor was made to not
9149 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9150 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9151 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9152 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9153 // spending transaction until height N+1 (or greater). This was due to the way
9154 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9155 // spending transaction at the height the input transaction was confirmed at, not whether we
9156 // should broadcast a spending transaction at the current height.
9157 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9158 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9159 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9160 // until we learned about an additional block.
9162 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9163 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9164 let chanmon_cfgs = create_chanmon_cfgs(3);
9165 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9166 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9167 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9168 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9170 create_announced_chan_between_nodes(&nodes, 0, 1);
9171 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9172 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9173 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9174 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9176 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9177 check_closed_broadcast!(nodes[1], true);
9178 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9179 check_added_monitors!(nodes[1], 1);
9180 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9181 assert_eq!(node_txn.len(), 1);
9183 let conf_height = nodes[1].best_block_info().1;
9184 if !test_height_before_timelock {
9185 connect_blocks(&nodes[1], 24 * 6);
9187 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9188 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9189 if test_height_before_timelock {
9190 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9191 // generate any events or broadcast any transactions
9192 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9193 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9195 // We should broadcast an HTLC transaction spending our funding transaction first
9196 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9197 assert_eq!(spending_txn.len(), 2);
9198 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9199 check_spends!(spending_txn[1], node_txn[0]);
9200 // We should also generate a SpendableOutputs event with the to_self output (as its
9202 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9203 assert_eq!(descriptor_spend_txn.len(), 1);
9205 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9206 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9207 // additional block built on top of the current chain.
9208 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9209 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9210 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 }]);
9211 check_added_monitors!(nodes[1], 1);
9213 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9214 assert!(updates.update_add_htlcs.is_empty());
9215 assert!(updates.update_fulfill_htlcs.is_empty());
9216 assert_eq!(updates.update_fail_htlcs.len(), 1);
9217 assert!(updates.update_fail_malformed_htlcs.is_empty());
9218 assert!(updates.update_fee.is_none());
9219 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9220 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9221 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9226 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9227 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9228 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9231 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9232 let chanmon_cfgs = create_chanmon_cfgs(2);
9233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9237 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9239 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9240 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9241 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9243 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9246 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9247 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9248 check_added_monitors!(nodes[0], 1);
9249 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9250 assert_eq!(events.len(), 1);
9251 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9252 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9253 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9255 expect_pending_htlcs_forwardable!(nodes[1]);
9256 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9259 // Note that we use a different PaymentId here to allow us to duplicativly pay
9260 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9261 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9262 check_added_monitors!(nodes[0], 1);
9263 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9264 assert_eq!(events.len(), 1);
9265 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9266 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9267 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9268 // At this point, nodes[1] would notice it has too much value for the payment. It will
9269 // assume the second is a privacy attack (no longer particularly relevant
9270 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9271 // the first HTLC delivered above.
9274 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9275 nodes[1].node.process_pending_htlc_forwards();
9277 if test_for_second_fail_panic {
9278 // Now we go fail back the first HTLC from the user end.
9279 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9281 let expected_destinations = vec![
9282 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9283 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9285 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9286 nodes[1].node.process_pending_htlc_forwards();
9288 check_added_monitors!(nodes[1], 1);
9289 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9290 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9292 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9293 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9294 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9296 let failure_events = nodes[0].node.get_and_clear_pending_events();
9297 assert_eq!(failure_events.len(), 4);
9298 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9299 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9300 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9301 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9303 // Let the second HTLC fail and claim the first
9304 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9305 nodes[1].node.process_pending_htlc_forwards();
9307 check_added_monitors!(nodes[1], 1);
9308 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9309 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9310 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9312 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9314 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9319 fn test_dup_htlc_second_fail_panic() {
9320 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9321 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9322 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9323 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9324 do_test_dup_htlc_second_rejected(true);
9328 fn test_dup_htlc_second_rejected() {
9329 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9330 // simply reject the second HTLC but are still able to claim the first HTLC.
9331 do_test_dup_htlc_second_rejected(false);
9335 fn test_inconsistent_mpp_params() {
9336 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9337 // such HTLC and allow the second to stay.
9338 let chanmon_cfgs = create_chanmon_cfgs(4);
9339 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9340 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9341 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9343 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9344 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9345 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9346 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9348 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9349 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9350 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9351 assert_eq!(route.paths.len(), 2);
9352 route.paths.sort_by(|path_a, _| {
9353 // Sort the path so that the path through nodes[1] comes first
9354 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9355 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9358 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9360 let cur_height = nodes[0].best_block_info().1;
9361 let payment_id = PaymentId([42; 32]);
9363 let session_privs = {
9364 // We create a fake route here so that we start with three pending HTLCs, which we'll
9365 // ultimately have, just not right away.
9366 let mut dup_route = route.clone();
9367 dup_route.paths.push(route.paths[1].clone());
9368 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9369 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9371 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9372 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9373 &None, session_privs[0]).unwrap();
9374 check_added_monitors!(nodes[0], 1);
9377 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9378 assert_eq!(events.len(), 1);
9379 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9381 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9383 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9384 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9385 check_added_monitors!(nodes[0], 1);
9388 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9389 assert_eq!(events.len(), 1);
9390 let payment_event = SendEvent::from_event(events.pop().unwrap());
9392 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9393 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9395 expect_pending_htlcs_forwardable!(nodes[2]);
9396 check_added_monitors!(nodes[2], 1);
9398 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9399 assert_eq!(events.len(), 1);
9400 let payment_event = SendEvent::from_event(events.pop().unwrap());
9402 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9403 check_added_monitors!(nodes[3], 0);
9404 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9406 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9407 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9408 // post-payment_secrets) and fail back the new HTLC.
9410 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9411 nodes[3].node.process_pending_htlc_forwards();
9412 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9413 nodes[3].node.process_pending_htlc_forwards();
9415 check_added_monitors!(nodes[3], 1);
9417 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9418 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9419 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9421 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 }]);
9422 check_added_monitors!(nodes[2], 1);
9424 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9425 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9426 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9428 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9430 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9431 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9432 &None, session_privs[2]).unwrap();
9433 check_added_monitors!(nodes[0], 1);
9435 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9436 assert_eq!(events.len(), 1);
9437 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9439 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9440 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9444 fn test_keysend_payments_to_public_node() {
9445 let chanmon_cfgs = create_chanmon_cfgs(2);
9446 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9447 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9448 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9450 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9451 let network_graph = nodes[0].network_graph.clone();
9452 let payer_pubkey = nodes[0].node.get_our_node_id();
9453 let payee_pubkey = nodes[1].node.get_our_node_id();
9454 let route_params = RouteParameters {
9455 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9456 final_value_msat: 10000,
9458 let scorer = test_utils::TestScorer::new();
9459 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9460 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9462 let test_preimage = PaymentPreimage([42; 32]);
9463 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9464 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9465 check_added_monitors!(nodes[0], 1);
9466 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9467 assert_eq!(events.len(), 1);
9468 let event = events.pop().unwrap();
9469 let path = vec![&nodes[1]];
9470 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9471 claim_payment(&nodes[0], &path, test_preimage);
9475 fn test_keysend_payments_to_private_node() {
9476 let chanmon_cfgs = create_chanmon_cfgs(2);
9477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9479 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9481 let payer_pubkey = nodes[0].node.get_our_node_id();
9482 let payee_pubkey = nodes[1].node.get_our_node_id();
9484 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9485 let route_params = RouteParameters {
9486 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9487 final_value_msat: 10000,
9489 let network_graph = nodes[0].network_graph.clone();
9490 let first_hops = nodes[0].node.list_usable_channels();
9491 let scorer = test_utils::TestScorer::new();
9492 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9493 let route = find_route(
9494 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9495 nodes[0].logger, &scorer, &(), &random_seed_bytes
9498 let test_preimage = PaymentPreimage([42; 32]);
9499 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9500 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9501 check_added_monitors!(nodes[0], 1);
9502 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9503 assert_eq!(events.len(), 1);
9504 let event = events.pop().unwrap();
9505 let path = vec![&nodes[1]];
9506 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9507 claim_payment(&nodes[0], &path, test_preimage);
9511 fn test_double_partial_claim() {
9512 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9513 // time out, the sender resends only some of the MPP parts, then the user processes the
9514 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9516 let chanmon_cfgs = create_chanmon_cfgs(4);
9517 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9518 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9519 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9521 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9522 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9523 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9524 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9526 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9527 assert_eq!(route.paths.len(), 2);
9528 route.paths.sort_by(|path_a, _| {
9529 // Sort the path so that the path through nodes[1] comes first
9530 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9531 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9534 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9535 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9536 // amount of time to respond to.
9538 // Connect some blocks to time out the payment
9539 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9540 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9542 let failed_destinations = vec![
9543 HTLCDestination::FailedPayment { payment_hash },
9544 HTLCDestination::FailedPayment { payment_hash },
9546 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9548 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9550 // nodes[1] now retries one of the two paths...
9551 nodes[0].node.send_payment_with_route(&route, payment_hash,
9552 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9553 check_added_monitors!(nodes[0], 2);
9555 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9556 assert_eq!(events.len(), 2);
9557 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9558 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9560 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9561 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9562 nodes[3].node.claim_funds(payment_preimage);
9563 check_added_monitors!(nodes[3], 0);
9564 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9567 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9568 #[derive(Clone, Copy, PartialEq)]
9569 enum ExposureEvent {
9570 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9572 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9574 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9575 AtUpdateFeeOutbound,
9578 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9579 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9582 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9583 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9584 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9585 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9586 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9587 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9588 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9589 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9591 let chanmon_cfgs = create_chanmon_cfgs(2);
9592 let mut config = test_default_channel_config();
9593 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9596 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9598 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9599 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9600 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9601 open_channel.max_accepted_htlcs = 60;
9603 open_channel.dust_limit_satoshis = 546;
9605 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9606 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9607 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9609 let opt_anchors = false;
9611 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9614 let mut node_0_per_peer_lock;
9615 let mut node_0_peer_state_lock;
9616 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9617 chan.holder_dust_limit_satoshis = 546;
9620 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9621 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()));
9622 check_added_monitors!(nodes[1], 1);
9623 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9625 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()));
9626 check_added_monitors!(nodes[0], 1);
9627 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9629 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9630 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9631 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9633 let dust_buffer_feerate = {
9634 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9635 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9636 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9637 chan.get_dust_buffer_feerate(None) as u64
9639 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;
9640 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9642 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;
9643 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9645 let dust_htlc_on_counterparty_tx: u64 = 25;
9646 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9649 if dust_outbound_balance {
9650 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9651 // Outbound dust balance: 4372 sats
9652 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9653 for _ in 0..dust_outbound_htlc_on_holder_tx {
9654 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9655 nodes[0].node.send_payment_with_route(&route, payment_hash,
9656 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9659 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9660 // Inbound dust balance: 4372 sats
9661 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9662 for _ in 0..dust_inbound_htlc_on_holder_tx {
9663 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9667 if dust_outbound_balance {
9668 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9669 // Outbound dust balance: 5000 sats
9670 for _ in 0..dust_htlc_on_counterparty_tx {
9671 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9672 nodes[0].node.send_payment_with_route(&route, payment_hash,
9673 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9676 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9677 // Inbound dust balance: 5000 sats
9678 for _ in 0..dust_htlc_on_counterparty_tx {
9679 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9684 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9685 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9686 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9687 let mut config = UserConfig::default();
9688 // With default dust exposure: 5000 sats
9690 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9691 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9692 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9693 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9694 ), true, APIError::ChannelUnavailable { ref err },
9695 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_config.max_dust_htlc_exposure_msat)));
9697 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9698 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9699 ), true, APIError::ChannelUnavailable { ref err },
9700 assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat)));
9702 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9703 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 });
9704 nodes[1].node.send_payment_with_route(&route, payment_hash,
9705 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9706 check_added_monitors!(nodes[1], 1);
9707 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9708 assert_eq!(events.len(), 1);
9709 let payment_event = SendEvent::from_event(events.remove(0));
9710 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9711 // With default dust exposure: 5000 sats
9713 // Outbound dust balance: 6399 sats
9714 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9715 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9716 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);
9718 // Outbound dust balance: 5200 sats
9719 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_config.max_dust_htlc_exposure_msat), 1);
9721 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9722 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9723 nodes[0].node.send_payment_with_route(&route, payment_hash,
9724 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9726 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9727 *feerate_lock = *feerate_lock * 10;
9729 nodes[0].node.timer_tick_occurred();
9730 check_added_monitors!(nodes[0], 1);
9731 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9734 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9735 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9736 added_monitors.clear();
9740 fn test_max_dust_htlc_exposure() {
9741 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9742 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9743 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9744 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9745 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9746 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9747 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9748 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9749 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9750 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9751 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9752 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9756 fn test_non_final_funding_tx() {
9757 let chanmon_cfgs = create_chanmon_cfgs(2);
9758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9760 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9762 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9763 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9764 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9765 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9766 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9768 let best_height = nodes[0].node.best_block.read().unwrap().height();
9770 let chan_id = *nodes[0].network_chan_count.borrow();
9771 let events = nodes[0].node.get_and_clear_pending_events();
9772 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9773 assert_eq!(events.len(), 1);
9774 let mut tx = match events[0] {
9775 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9776 // Timelock the transaction _beyond_ the best client height + 1.
9777 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9778 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9781 _ => panic!("Unexpected event"),
9783 // Transaction should fail as it's evaluated as non-final for propagation.
9784 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9785 Err(APIError::APIMisuseError { err }) => {
9786 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9791 // However, transaction should be accepted if it's in a +1 headroom from best block.
9792 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9793 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9794 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9798 fn accept_busted_but_better_fee() {
9799 // If a peer sends us a fee update that is too low, but higher than our previous channel
9800 // feerate, we should accept it. In the future we may want to consider closing the channel
9801 // later, but for now we only accept the update.
9802 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9803 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9804 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9805 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9807 create_chan_between_nodes(&nodes[0], &nodes[1]);
9809 // Set nodes[1] to expect 5,000 sat/kW.
9811 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9812 *feerate_lock = 5000;
9815 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9817 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9818 *feerate_lock = 1000;
9820 nodes[0].node.timer_tick_occurred();
9821 check_added_monitors!(nodes[0], 1);
9823 let events = nodes[0].node.get_and_clear_pending_msg_events();
9824 assert_eq!(events.len(), 1);
9826 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9827 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9828 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9830 _ => panic!("Unexpected event"),
9833 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9836 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9837 *feerate_lock = 2000;
9839 nodes[0].node.timer_tick_occurred();
9840 check_added_monitors!(nodes[0], 1);
9842 let events = nodes[0].node.get_and_clear_pending_msg_events();
9843 assert_eq!(events.len(), 1);
9845 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9846 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9847 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9849 _ => panic!("Unexpected event"),
9852 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9855 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9856 *feerate_lock = 1000;
9858 nodes[0].node.timer_tick_occurred();
9859 check_added_monitors!(nodes[0], 1);
9861 let events = nodes[0].node.get_and_clear_pending_msg_events();
9862 assert_eq!(events.len(), 1);
9864 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9865 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9866 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9867 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9868 check_closed_broadcast!(nodes[1], true);
9869 check_added_monitors!(nodes[1], 1);
9871 _ => panic!("Unexpected event"),
9875 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9876 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9877 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9878 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9879 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9880 let min_final_cltv_expiry_delta = 120;
9881 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9882 min_final_cltv_expiry_delta - 2 };
9883 let recv_value = 100_000;
9885 create_chan_between_nodes(&nodes[0], &nodes[1]);
9887 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9888 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9889 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9890 Some(recv_value), Some(min_final_cltv_expiry_delta));
9891 (payment_hash, payment_preimage, payment_secret)
9893 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9894 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9896 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9897 nodes[0].node.send_payment_with_route(&route, payment_hash,
9898 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9899 check_added_monitors!(nodes[0], 1);
9900 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9901 assert_eq!(events.len(), 1);
9902 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9903 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9904 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9905 expect_pending_htlcs_forwardable!(nodes[1]);
9908 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9909 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9911 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9913 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9915 check_added_monitors!(nodes[1], 1);
9917 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9918 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9919 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9921 expect_payment_failed!(nodes[0], payment_hash, true);
9926 fn test_payment_with_custom_min_cltv_expiry_delta() {
9927 do_payment_with_custom_min_final_cltv_expiry(false, false);
9928 do_payment_with_custom_min_final_cltv_expiry(false, true);
9929 do_payment_with_custom_min_final_cltv_expiry(true, false);
9930 do_payment_with_custom_min_final_cltv_expiry(true, true);