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 { .. }, {});
1129 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132 // This should also be true if we try to forward a payment.
1133 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1135 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1136 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1137 check_added_monitors!(nodes[0], 1);
1140 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1141 assert_eq!(events.len(), 1);
1142 let payment_event = SendEvent::from_event(events.pop().unwrap());
1143 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1146 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1147 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1148 // fails), the second will process the resulting failure and fail the HTLC backward.
1149 expect_pending_htlcs_forwardable!(nodes[1]);
1150 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 }]);
1151 check_added_monitors!(nodes[1], 1);
1153 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1155 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1157 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1159 // Now forward all the pending HTLCs and claim them back
1160 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1161 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1162 check_added_monitors!(nodes[2], 1);
1164 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1165 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1166 check_added_monitors!(nodes[1], 1);
1167 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1169 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1170 check_added_monitors!(nodes[1], 1);
1171 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1173 for ref update in as_updates.update_add_htlcs.iter() {
1174 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1176 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1177 check_added_monitors!(nodes[2], 1);
1178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1179 check_added_monitors!(nodes[2], 1);
1180 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1182 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1183 check_added_monitors!(nodes[1], 1);
1184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1185 check_added_monitors!(nodes[1], 1);
1186 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1188 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1189 check_added_monitors!(nodes[2], 1);
1191 expect_pending_htlcs_forwardable!(nodes[2]);
1193 let events = nodes[2].node.get_and_clear_pending_events();
1194 assert_eq!(events.len(), payments.len());
1195 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1197 &Event::PaymentClaimable { ref payment_hash, .. } => {
1198 assert_eq!(*payment_hash, *hash);
1200 _ => panic!("Unexpected event"),
1204 for (preimage, _) in payments.drain(..) {
1205 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1208 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1212 fn duplicate_htlc_test() {
1213 // Test that we accept duplicate payment_hash HTLCs across the network and that
1214 // claiming/failing them are all separate and don't affect each other
1215 let chanmon_cfgs = create_chanmon_cfgs(6);
1216 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1217 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1218 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1220 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1221 create_announced_chan_between_nodes(&nodes, 0, 3);
1222 create_announced_chan_between_nodes(&nodes, 1, 3);
1223 create_announced_chan_between_nodes(&nodes, 2, 3);
1224 create_announced_chan_between_nodes(&nodes, 3, 4);
1225 create_announced_chan_between_nodes(&nodes, 3, 5);
1227 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1229 *nodes[0].network_payment_count.borrow_mut() -= 1;
1230 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1232 *nodes[0].network_payment_count.borrow_mut() -= 1;
1233 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1235 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1236 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1237 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1241 fn test_duplicate_htlc_different_direction_onchain() {
1242 // Test that ChannelMonitor doesn't generate 2 preimage txn
1243 // when we have 2 HTLCs with same preimage that go across a node
1244 // in opposite directions, even with the same payment secret.
1245 let chanmon_cfgs = create_chanmon_cfgs(2);
1246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1255 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1257 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1258 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1259 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1261 // Provide preimage to node 0 by claiming payment
1262 nodes[0].node.claim_funds(payment_preimage);
1263 expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1264 check_added_monitors!(nodes[0], 1);
1266 // Broadcast node 1 commitment txn
1267 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1269 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1270 let mut has_both_htlcs = 0; // check htlcs match ones committed
1271 for outp in remote_txn[0].output.iter() {
1272 if outp.value == 800_000 / 1000 {
1273 has_both_htlcs += 1;
1274 } else if outp.value == 900_000 / 1000 {
1275 has_both_htlcs += 1;
1278 assert_eq!(has_both_htlcs, 2);
1280 mine_transaction(&nodes[0], &remote_txn[0]);
1281 check_added_monitors!(nodes[0], 1);
1282 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1283 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1285 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1286 assert_eq!(claim_txn.len(), 3);
1288 check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1289 check_spends!(claim_txn[1], remote_txn[0]);
1290 check_spends!(claim_txn[2], remote_txn[0]);
1291 let preimage_tx = &claim_txn[0];
1292 let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1293 (&claim_txn[1], &claim_txn[2])
1295 (&claim_txn[2], &claim_txn[1])
1298 assert_eq!(preimage_tx.input.len(), 1);
1299 assert_eq!(preimage_bump_tx.input.len(), 1);
1301 assert_eq!(preimage_tx.input.len(), 1);
1302 assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1303 assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1305 assert_eq!(timeout_tx.input.len(), 1);
1306 assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1307 check_spends!(timeout_tx, remote_txn[0]);
1308 assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1310 let events = nodes[0].node.get_and_clear_pending_msg_events();
1311 assert_eq!(events.len(), 3);
1314 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1315 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1316 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1317 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1319 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, .. } } => {
1320 assert!(update_add_htlcs.is_empty());
1321 assert!(update_fail_htlcs.is_empty());
1322 assert_eq!(update_fulfill_htlcs.len(), 1);
1323 assert!(update_fail_malformed_htlcs.is_empty());
1324 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1326 _ => panic!("Unexpected event"),
1332 fn test_basic_channel_reserve() {
1333 let chanmon_cfgs = create_chanmon_cfgs(2);
1334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1337 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1339 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1340 let channel_reserve = chan_stat.channel_reserve_msat;
1342 // The 2* and +1 are for the fee spike reserve.
1343 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));
1344 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1345 let (mut route, our_payment_hash, _, our_payment_secret) =
1346 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1347 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1348 let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1349 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1351 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1352 if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1353 else { panic!("Unexpected error variant"); }
1355 _ => panic!("Unexpected error variant"),
1357 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1359 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1363 fn test_fee_spike_violation_fails_htlc() {
1364 let chanmon_cfgs = create_chanmon_cfgs(2);
1365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1367 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1368 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1370 let (mut route, payment_hash, _, payment_secret) =
1371 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1372 route.paths[0].hops[0].fee_msat += 1;
1373 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1374 let secp_ctx = Secp256k1::new();
1375 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1377 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1379 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1380 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1381 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1382 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1383 let msg = msgs::UpdateAddHTLC {
1386 amount_msat: htlc_msat,
1387 payment_hash: payment_hash,
1388 cltv_expiry: htlc_cltv,
1389 onion_routing_packet: onion_packet,
1392 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1394 // Now manually create the commitment_signed message corresponding to the update_add
1395 // nodes[0] just sent. In the code for construction of this message, "local" refers
1396 // to the sender of the message, and "remote" refers to the receiver.
1398 let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1400 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1402 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1403 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1404 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1405 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1406 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1407 let local_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1408 let chan_signer = local_chan.get_signer();
1409 // Make the signer believe we validated another commitment, so we can release the secret
1410 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1412 let pubkeys = chan_signer.pubkeys();
1413 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1414 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1415 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1416 chan_signer.pubkeys().funding_pubkey)
1418 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1419 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1420 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1421 let remote_chan = chan_lock.channel_by_id.get(&chan.2).unwrap();
1422 let chan_signer = remote_chan.get_signer();
1423 let pubkeys = chan_signer.pubkeys();
1424 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1425 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1426 chan_signer.pubkeys().funding_pubkey)
1429 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1430 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1431 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1433 // Build the remote commitment transaction so we can sign it, and then later use the
1434 // signature for the commitment_signed message.
1435 let local_chan_balance = 1313;
1437 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1439 amount_msat: 3460001,
1440 cltv_expiry: htlc_cltv,
1442 transaction_output_index: Some(1),
1445 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1448 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1449 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1450 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).unwrap();
1451 let local_chan_signer = local_chan.get_signer();
1452 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1456 local_chan.opt_anchors(), local_funding, remote_funding,
1457 commit_tx_keys.clone(),
1459 &mut vec![(accepted_htlc_info, ())],
1460 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1462 local_chan_signer.sign_counterparty_commitment(&commitment_tx, Vec::new(), &secp_ctx).unwrap()
1465 let commit_signed_msg = msgs::CommitmentSigned {
1468 htlc_signatures: res.1,
1470 partial_signature_with_nonce: None,
1473 // Send the commitment_signed message to the nodes[1].
1474 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1475 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1477 // Send the RAA to nodes[1].
1478 let raa_msg = msgs::RevokeAndACK {
1480 per_commitment_secret: local_secret,
1481 next_per_commitment_point: next_local_point,
1483 next_local_nonce: None,
1485 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1487 let events = nodes[1].node.get_and_clear_pending_msg_events();
1488 assert_eq!(events.len(), 1);
1489 // Make sure the HTLC failed in the way we expect.
1491 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1492 assert_eq!(update_fail_htlcs.len(), 1);
1493 update_fail_htlcs[0].clone()
1495 _ => panic!("Unexpected event"),
1497 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1498 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1500 check_added_monitors!(nodes[1], 2);
1504 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1505 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1506 // Set the fee rate for the channel very high, to the point where the fundee
1507 // sending any above-dust amount would result in a channel reserve violation.
1508 // In this test we check that we would be prevented from sending an HTLC in
1510 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1514 let default_config = UserConfig::default();
1515 let opt_anchors = false;
1517 let mut push_amt = 100_000_000;
1518 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1520 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1522 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1524 // Fetch a route in advance as we will be unable to once we're unable to send.
1525 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1526 // Sending exactly enough to hit the reserve amount should be accepted
1527 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1528 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1531 // However one more HTLC should be significantly over the reserve amount and fail.
1532 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1533 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1534 ), true, APIError::ChannelUnavailable { .. }, {});
1535 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1539 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1540 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1545 let default_config = UserConfig::default();
1546 let opt_anchors = false;
1548 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1549 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1550 // transaction fee with 0 HTLCs (183 sats)).
1551 let mut push_amt = 100_000_000;
1552 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1553 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1554 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1556 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1557 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1558 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1561 let (mut route, payment_hash, _, payment_secret) =
1562 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1563 route.paths[0].hops[0].fee_msat = 700_000;
1564 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1565 let secp_ctx = Secp256k1::new();
1566 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1567 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1568 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1569 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1570 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1571 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1572 let msg = msgs::UpdateAddHTLC {
1574 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1575 amount_msat: htlc_msat,
1576 payment_hash: payment_hash,
1577 cltv_expiry: htlc_cltv,
1578 onion_routing_packet: onion_packet,
1581 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1582 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1583 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);
1584 assert_eq!(nodes[0].node.list_channels().len(), 0);
1585 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1586 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1587 check_added_monitors!(nodes[0], 1);
1588 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() });
1592 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1593 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1594 // calculating our commitment transaction fee (this was previously broken).
1595 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1596 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1600 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1601 let default_config = UserConfig::default();
1602 let opt_anchors = false;
1604 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1605 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1606 // transaction fee with 0 HTLCs (183 sats)).
1607 let mut push_amt = 100_000_000;
1608 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1609 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1610 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1612 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1613 + feerate_per_kw as u64 * htlc_success_tx_weight(opt_anchors) / 1000 * 1000 - 1;
1614 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1615 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1616 // commitment transaction fee.
1617 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1619 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1620 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1621 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1624 // One more than the dust amt should fail, however.
1625 let (mut route, our_payment_hash, _, our_payment_secret) =
1626 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1627 route.paths[0].hops[0].fee_msat += 1;
1628 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1629 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1630 ), true, APIError::ChannelUnavailable { .. }, {});
1634 fn test_chan_init_feerate_unaffordability() {
1635 // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1636 // channel reserve and feerate requirements.
1637 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1638 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1642 let default_config = UserConfig::default();
1643 let opt_anchors = false;
1645 // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1647 let mut push_amt = 100_000_000;
1648 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, opt_anchors);
1649 assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None).unwrap_err(),
1650 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1652 // During open, we don't have a "counterparty channel reserve" to check against, so that
1653 // requirement only comes into play on the open_channel handling side.
1654 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1655 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None).unwrap();
1656 let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1657 open_channel_msg.push_msat += 1;
1658 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1660 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1661 assert_eq!(msg_events.len(), 1);
1662 match msg_events[0] {
1663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1664 assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1666 _ => panic!("Unexpected event"),
1671 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1672 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1673 // calculating our counterparty's commitment transaction fee (this was previously broken).
1674 let chanmon_cfgs = create_chanmon_cfgs(2);
1675 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1676 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1677 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1678 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1680 let payment_amt = 46000; // Dust amount
1681 // In the previous code, these first four payments would succeed.
1682 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1683 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1684 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1685 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1687 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1688 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1689 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1690 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1691 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1692 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1694 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1695 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1696 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1697 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1701 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1702 let chanmon_cfgs = create_chanmon_cfgs(3);
1703 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1704 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1705 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1706 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1707 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1710 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1712 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1713 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
1715 // Add a 2* and +1 for the fee spike reserve.
1716 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1717 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;
1718 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1720 // Add a pending HTLC.
1721 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1722 let payment_event_1 = {
1723 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1724 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1725 check_added_monitors!(nodes[0], 1);
1727 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1728 assert_eq!(events.len(), 1);
1729 SendEvent::from_event(events.remove(0))
1731 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1733 // Attempt to trigger a channel reserve violation --> payment failure.
1734 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, opt_anchors);
1735 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;
1736 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1737 let mut route_2 = route_1.clone();
1738 route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1740 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1741 let secp_ctx = Secp256k1::new();
1742 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1743 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1744 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1745 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1746 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1747 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1748 let msg = msgs::UpdateAddHTLC {
1751 amount_msat: htlc_msat + 1,
1752 payment_hash: our_payment_hash_1,
1753 cltv_expiry: htlc_cltv,
1754 onion_routing_packet: onion_packet,
1757 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1758 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1759 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1760 assert_eq!(nodes[1].node.list_channels().len(), 1);
1761 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1762 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1763 check_added_monitors!(nodes[1], 1);
1764 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1768 fn test_inbound_outbound_capacity_is_not_zero() {
1769 let chanmon_cfgs = create_chanmon_cfgs(2);
1770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1772 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1773 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1774 let channels0 = node_chanmgrs[0].list_channels();
1775 let channels1 = node_chanmgrs[1].list_channels();
1776 let default_config = UserConfig::default();
1777 assert_eq!(channels0.len(), 1);
1778 assert_eq!(channels1.len(), 1);
1780 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1781 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1782 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1784 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1785 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1788 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, opt_anchors: bool) -> u64 {
1789 (commitment_tx_base_weight(opt_anchors) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1793 fn test_channel_reserve_holding_cell_htlcs() {
1794 let chanmon_cfgs = create_chanmon_cfgs(3);
1795 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1796 // When this test was written, the default base fee floated based on the HTLC count.
1797 // It is now fixed, so we simply set the fee to the expected value here.
1798 let mut config = test_default_channel_config();
1799 config.channel_config.forwarding_fee_base_msat = 239;
1800 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1801 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1802 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1803 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1805 let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1806 let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1808 let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1809 let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1811 macro_rules! expect_forward {
1813 let mut events = $node.node.get_and_clear_pending_msg_events();
1814 assert_eq!(events.len(), 1);
1815 check_added_monitors!($node, 1);
1816 let payment_event = SendEvent::from_event(events.remove(0));
1821 let feemsat = 239; // set above
1822 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1823 let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1824 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_1.2);
1826 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1828 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1830 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1831 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1832 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1833 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1834 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1836 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1837 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1838 ), true, APIError::ChannelUnavailable { .. }, {});
1839 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1842 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1843 // nodes[0]'s wealth
1845 let amt_msat = recv_value_0 + total_fee_msat;
1846 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1847 // Also, ensure that each payment has enough to be over the dust limit to
1848 // ensure it'll be included in each commit tx fee calculation.
1849 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1850 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1851 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1855 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1856 .with_bolt11_features(nodes[2].node.invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1857 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1858 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1859 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1861 let (stat01_, stat11_, stat12_, stat22_) = (
1862 get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1863 get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1864 get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1865 get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1868 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1869 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1870 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1871 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1872 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1875 // adding pending output.
1876 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1877 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1878 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1879 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1880 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1881 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1882 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1883 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1884 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1886 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors);
1887 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1888 let amt_msat_1 = recv_value_1 + total_fee_msat;
1890 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);
1891 let payment_event_1 = {
1892 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1893 RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1894 check_added_monitors!(nodes[0], 1);
1896 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1897 assert_eq!(events.len(), 1);
1898 SendEvent::from_event(events.remove(0))
1900 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1902 // channel reserve test with htlc pending output > 0
1903 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1905 let mut route = route_1.clone();
1906 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1907 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1908 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1909 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1910 ), true, APIError::ChannelUnavailable { .. }, {});
1911 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1914 // split the rest to test holding cell
1915 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, opt_anchors);
1916 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1917 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1918 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1920 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1921 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);
1924 // now see if they go through on both sides
1925 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);
1926 // but this will stuck in the holding cell
1927 nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1928 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1929 check_added_monitors!(nodes[0], 0);
1930 let events = nodes[0].node.get_and_clear_pending_events();
1931 assert_eq!(events.len(), 0);
1933 // test with outbound holding cell amount > 0
1935 let (mut route, our_payment_hash, _, our_payment_secret) =
1936 get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1937 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1938 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1939 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1940 ), true, APIError::ChannelUnavailable { .. }, {});
1941 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1944 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);
1945 // this will also stuck in the holding cell
1946 nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1947 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1948 check_added_monitors!(nodes[0], 0);
1949 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1950 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1952 // flush the pending htlc
1953 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1954 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1955 check_added_monitors!(nodes[1], 1);
1957 // the pending htlc should be promoted to committed
1958 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1959 check_added_monitors!(nodes[0], 1);
1960 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1962 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1963 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1964 // No commitment_signed so get_event_msg's assert(len == 1) passes
1965 check_added_monitors!(nodes[0], 1);
1967 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1968 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1969 check_added_monitors!(nodes[1], 1);
1971 expect_pending_htlcs_forwardable!(nodes[1]);
1973 let ref payment_event_11 = expect_forward!(nodes[1]);
1974 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1975 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1977 expect_pending_htlcs_forwardable!(nodes[2]);
1978 expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1980 // flush the htlcs in the holding cell
1981 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1982 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1984 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1985 expect_pending_htlcs_forwardable!(nodes[1]);
1987 let ref payment_event_3 = expect_forward!(nodes[1]);
1988 assert_eq!(payment_event_3.msgs.len(), 2);
1989 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1990 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1992 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1993 expect_pending_htlcs_forwardable!(nodes[2]);
1995 let events = nodes[2].node.get_and_clear_pending_events();
1996 assert_eq!(events.len(), 2);
1998 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
1999 assert_eq!(our_payment_hash_21, *payment_hash);
2000 assert_eq!(recv_value_21, amount_msat);
2001 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2002 assert_eq!(via_channel_id, Some(chan_2.2));
2004 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2005 assert!(payment_preimage.is_none());
2006 assert_eq!(our_payment_secret_21, *payment_secret);
2008 _ => panic!("expected PaymentPurpose::InvoicePayment")
2011 _ => panic!("Unexpected event"),
2014 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2015 assert_eq!(our_payment_hash_22, *payment_hash);
2016 assert_eq!(recv_value_22, amount_msat);
2017 assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2018 assert_eq!(via_channel_id, Some(chan_2.2));
2020 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2021 assert!(payment_preimage.is_none());
2022 assert_eq!(our_payment_secret_22, *payment_secret);
2024 _ => panic!("expected PaymentPurpose::InvoicePayment")
2027 _ => panic!("Unexpected event"),
2030 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2031 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2034 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, opt_anchors);
2035 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2036 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2038 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
2039 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);
2040 let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2041 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2042 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2044 let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2045 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2049 fn channel_reserve_in_flight_removes() {
2050 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2051 // can send to its counterparty, but due to update ordering, the other side may not yet have
2052 // considered those HTLCs fully removed.
2053 // This tests that we don't count HTLCs which will not be included in the next remote
2054 // commitment transaction towards the reserve value (as it implies no commitment transaction
2055 // will be generated which violates the remote reserve value).
2056 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2058 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2059 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2060 // you only consider the value of the first HTLC, it may not),
2061 // * start routing a third HTLC from A to B,
2062 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2063 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2064 // * deliver the first fulfill from B
2065 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2067 // * deliver A's response CS and RAA.
2068 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2069 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2070 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2071 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2072 let chanmon_cfgs = create_chanmon_cfgs(2);
2073 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2074 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2075 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2076 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2078 let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2079 // Route the first two HTLCs.
2080 let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2081 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2082 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2084 // Start routing the third HTLC (this is just used to get everyone in the right state).
2085 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2087 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2088 RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2089 check_added_monitors!(nodes[0], 1);
2090 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2091 assert_eq!(events.len(), 1);
2092 SendEvent::from_event(events.remove(0))
2095 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2096 // initial fulfill/CS.
2097 nodes[1].node.claim_funds(payment_preimage_1);
2098 expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2099 check_added_monitors!(nodes[1], 1);
2100 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2102 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2103 // remove the second HTLC when we send the HTLC back from B to A.
2104 nodes[1].node.claim_funds(payment_preimage_2);
2105 expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2106 check_added_monitors!(nodes[1], 1);
2107 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2109 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2110 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2111 check_added_monitors!(nodes[0], 1);
2112 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2113 expect_payment_sent_without_paths!(nodes[0], payment_preimage_1);
2115 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2116 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2117 check_added_monitors!(nodes[1], 1);
2118 // B is already AwaitingRAA, so cant generate a CS here
2119 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2121 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2122 check_added_monitors!(nodes[1], 1);
2123 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2125 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2126 check_added_monitors!(nodes[0], 1);
2127 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2129 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2130 check_added_monitors!(nodes[1], 1);
2131 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2133 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2134 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2135 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2136 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2137 // on-chain as necessary).
2138 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2139 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2140 check_added_monitors!(nodes[0], 1);
2141 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2142 expect_payment_sent_without_paths!(nodes[0], payment_preimage_2);
2144 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2145 check_added_monitors!(nodes[1], 1);
2146 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2148 expect_pending_htlcs_forwardable!(nodes[1]);
2149 expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2151 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2152 // resolve the second HTLC from A's point of view.
2153 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2154 check_added_monitors!(nodes[0], 1);
2155 expect_payment_path_successful!(nodes[0]);
2156 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2158 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2159 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2160 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2162 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2163 RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2164 check_added_monitors!(nodes[1], 1);
2165 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2166 assert_eq!(events.len(), 1);
2167 SendEvent::from_event(events.remove(0))
2170 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2171 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2172 check_added_monitors!(nodes[0], 1);
2173 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2175 // Now just resolve all the outstanding messages/HTLCs for completeness...
2177 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2178 check_added_monitors!(nodes[1], 1);
2179 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2181 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2182 check_added_monitors!(nodes[1], 1);
2184 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2185 check_added_monitors!(nodes[0], 1);
2186 expect_payment_path_successful!(nodes[0]);
2187 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2189 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2190 check_added_monitors!(nodes[1], 1);
2191 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2193 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2194 check_added_monitors!(nodes[0], 1);
2196 expect_pending_htlcs_forwardable!(nodes[0]);
2197 expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2199 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2200 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2204 fn channel_monitor_network_test() {
2205 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2206 // tests that ChannelMonitor is able to recover from various states.
2207 let chanmon_cfgs = create_chanmon_cfgs(5);
2208 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2209 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2210 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2212 // Create some initial channels
2213 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2214 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2215 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2216 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2218 // Make sure all nodes are at the same starting height
2219 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2220 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2221 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2222 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2223 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2225 // Rebalance the network a bit by relaying one payment through all the channels...
2226 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2227 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2228 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2229 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2231 // Simple case with no pending HTLCs:
2232 nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2233 check_added_monitors!(nodes[1], 1);
2234 check_closed_broadcast!(nodes[1], true);
2236 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2237 assert_eq!(node_txn.len(), 1);
2238 mine_transaction(&nodes[0], &node_txn[0]);
2239 check_added_monitors!(nodes[0], 1);
2240 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2242 check_closed_broadcast!(nodes[0], true);
2243 assert_eq!(nodes[0].node.list_channels().len(), 0);
2244 assert_eq!(nodes[1].node.list_channels().len(), 1);
2245 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2246 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2248 // One pending HTLC is discarded by the force-close:
2249 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2251 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2252 // broadcasted until we reach the timelock time).
2253 nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2254 check_closed_broadcast!(nodes[1], true);
2255 check_added_monitors!(nodes[1], 1);
2257 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2258 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2259 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2260 mine_transaction(&nodes[2], &node_txn[0]);
2261 check_added_monitors!(nodes[2], 1);
2262 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2264 check_closed_broadcast!(nodes[2], true);
2265 assert_eq!(nodes[1].node.list_channels().len(), 0);
2266 assert_eq!(nodes[2].node.list_channels().len(), 1);
2267 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
2268 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2270 macro_rules! claim_funds {
2271 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2273 $node.node.claim_funds($preimage);
2274 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2275 check_added_monitors!($node, 1);
2277 let events = $node.node.get_and_clear_pending_msg_events();
2278 assert_eq!(events.len(), 1);
2280 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2281 assert!(update_add_htlcs.is_empty());
2282 assert!(update_fail_htlcs.is_empty());
2283 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2285 _ => panic!("Unexpected event"),
2291 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2292 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2293 nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2294 check_added_monitors!(nodes[2], 1);
2295 check_closed_broadcast!(nodes[2], true);
2296 let node2_commitment_txid;
2298 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2299 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2300 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2301 node2_commitment_txid = node_txn[0].txid();
2303 // Claim the payment on nodes[3], giving it knowledge of the preimage
2304 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2305 mine_transaction(&nodes[3], &node_txn[0]);
2306 check_added_monitors!(nodes[3], 1);
2307 check_preimage_claim(&nodes[3], &node_txn);
2309 check_closed_broadcast!(nodes[3], true);
2310 assert_eq!(nodes[2].node.list_channels().len(), 0);
2311 assert_eq!(nodes[3].node.list_channels().len(), 1);
2312 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
2313 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2315 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2316 // confusing us in the following tests.
2317 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2319 // One pending HTLC to time out:
2320 let (payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2321 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2324 let (close_chan_update_1, close_chan_update_2) = {
2325 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2326 let events = nodes[3].node.get_and_clear_pending_msg_events();
2327 assert_eq!(events.len(), 2);
2328 let close_chan_update_1 = match events[0] {
2329 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2332 _ => panic!("Unexpected event"),
2335 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2336 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2338 _ => panic!("Unexpected event"),
2340 check_added_monitors!(nodes[3], 1);
2342 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2344 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2345 node_txn.retain(|tx| {
2346 if tx.input[0].previous_output.txid == node2_commitment_txid {
2352 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2354 // Claim the payment on nodes[4], giving it knowledge of the preimage
2355 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2357 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2358 let events = nodes[4].node.get_and_clear_pending_msg_events();
2359 assert_eq!(events.len(), 2);
2360 let close_chan_update_2 = match events[0] {
2361 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2364 _ => panic!("Unexpected event"),
2367 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2368 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2370 _ => panic!("Unexpected event"),
2372 check_added_monitors!(nodes[4], 1);
2373 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2375 mine_transaction(&nodes[4], &node_txn[0]);
2376 check_preimage_claim(&nodes[4], &node_txn);
2377 (close_chan_update_1, close_chan_update_2)
2379 nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2380 nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2381 assert_eq!(nodes[3].node.list_channels().len(), 0);
2382 assert_eq!(nodes[4].node.list_channels().len(), 0);
2384 assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2385 ChannelMonitorUpdateStatus::Completed);
2386 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2387 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2391 fn test_justice_tx_htlc_timeout() {
2392 // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2393 let mut alice_config = UserConfig::default();
2394 alice_config.channel_handshake_config.announced_channel = true;
2395 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2396 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2397 let mut bob_config = UserConfig::default();
2398 bob_config.channel_handshake_config.announced_channel = true;
2399 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2400 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2401 let user_cfgs = [Some(alice_config), Some(bob_config)];
2402 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2403 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2404 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2407 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2408 // Create some new channels:
2409 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2411 // A pending HTLC which will be revoked:
2412 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2413 // Get the will-be-revoked local txn from nodes[0]
2414 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2415 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2416 assert_eq!(revoked_local_txn[0].input.len(), 1);
2417 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2418 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2419 assert_eq!(revoked_local_txn[1].input.len(), 1);
2420 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2421 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2422 // Revoke the old state
2423 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2426 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2428 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2429 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2430 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2431 check_spends!(node_txn[0], revoked_local_txn[0]);
2432 node_txn.swap_remove(0);
2434 check_added_monitors!(nodes[1], 1);
2435 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2436 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2438 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2439 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2440 // Verify broadcast of revoked HTLC-timeout
2441 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2442 check_added_monitors!(nodes[0], 1);
2443 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2444 // Broadcast revoked HTLC-timeout on node 1
2445 mine_transaction(&nodes[1], &node_txn[1]);
2446 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2448 get_announce_close_broadcast_events(&nodes, 0, 1);
2449 assert_eq!(nodes[0].node.list_channels().len(), 0);
2450 assert_eq!(nodes[1].node.list_channels().len(), 0);
2454 fn test_justice_tx_htlc_success() {
2455 // Test justice txn built on revoked HTLC-Success tx, against both sides
2456 let mut alice_config = UserConfig::default();
2457 alice_config.channel_handshake_config.announced_channel = true;
2458 alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2459 alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2460 let mut bob_config = UserConfig::default();
2461 bob_config.channel_handshake_config.announced_channel = true;
2462 bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2463 bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2464 let user_cfgs = [Some(alice_config), Some(bob_config)];
2465 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2466 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2467 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2470 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2471 // Create some new channels:
2472 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2474 // A pending HTLC which will be revoked:
2475 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2476 // Get the will-be-revoked local txn from B
2477 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2478 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2479 assert_eq!(revoked_local_txn[0].input.len(), 1);
2480 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2481 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2482 // Revoke the old state
2483 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2485 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2487 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2488 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2489 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2491 check_spends!(node_txn[0], revoked_local_txn[0]);
2492 node_txn.swap_remove(0);
2494 check_added_monitors!(nodes[0], 1);
2495 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2497 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2498 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2499 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2500 check_added_monitors!(nodes[1], 1);
2501 mine_transaction(&nodes[0], &node_txn[1]);
2502 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2503 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2505 get_announce_close_broadcast_events(&nodes, 0, 1);
2506 assert_eq!(nodes[0].node.list_channels().len(), 0);
2507 assert_eq!(nodes[1].node.list_channels().len(), 0);
2511 fn revoked_output_claim() {
2512 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2513 // transaction is broadcast by its counterparty
2514 let chanmon_cfgs = create_chanmon_cfgs(2);
2515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2518 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2520 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2521 assert_eq!(revoked_local_txn.len(), 1);
2522 // Only output is the full channel value back to nodes[0]:
2523 assert_eq!(revoked_local_txn[0].output.len(), 1);
2524 // Send a payment through, updating everyone's latest commitment txn
2525 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2527 // Inform nodes[1] that nodes[0] broadcast a stale tx
2528 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2529 check_added_monitors!(nodes[1], 1);
2530 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2531 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2532 assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2534 check_spends!(node_txn[0], revoked_local_txn[0]);
2536 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2537 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2538 get_announce_close_broadcast_events(&nodes, 0, 1);
2539 check_added_monitors!(nodes[0], 1);
2540 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2544 fn claim_htlc_outputs_shared_tx() {
2545 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2546 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2547 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2550 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2552 // Create some new channel:
2553 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2555 // Rebalance the network to generate htlc in the two directions
2556 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2557 // 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
2558 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2559 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2561 // Get the will-be-revoked local txn from node[0]
2562 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2563 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2564 assert_eq!(revoked_local_txn[0].input.len(), 1);
2565 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2566 assert_eq!(revoked_local_txn[1].input.len(), 1);
2567 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2568 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2569 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2571 //Revoke the old state
2572 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2575 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2576 check_added_monitors!(nodes[0], 1);
2577 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2578 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2579 check_added_monitors!(nodes[1], 1);
2580 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2581 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2582 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2584 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2585 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2587 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2588 check_spends!(node_txn[0], revoked_local_txn[0]);
2590 let mut witness_lens = BTreeSet::new();
2591 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2592 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2593 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2594 assert_eq!(witness_lens.len(), 3);
2595 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2596 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2597 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2599 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2600 // ANTI_REORG_DELAY confirmations.
2601 mine_transaction(&nodes[1], &node_txn[0]);
2602 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2603 expect_payment_failed!(nodes[1], payment_hash_2, false);
2605 get_announce_close_broadcast_events(&nodes, 0, 1);
2606 assert_eq!(nodes[0].node.list_channels().len(), 0);
2607 assert_eq!(nodes[1].node.list_channels().len(), 0);
2611 fn claim_htlc_outputs_single_tx() {
2612 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2613 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2614 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2617 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2619 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2621 // Rebalance the network to generate htlc in the two directions
2622 send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2623 // 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
2624 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2625 let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2626 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2628 // Get the will-be-revoked local txn from node[0]
2629 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2631 //Revoke the old state
2632 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2635 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2636 check_added_monitors!(nodes[0], 1);
2637 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2638 check_added_monitors!(nodes[1], 1);
2639 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2640 let mut events = nodes[0].node.get_and_clear_pending_events();
2641 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2642 match events.last().unwrap() {
2643 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2644 _ => panic!("Unexpected event"),
2647 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2648 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2650 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2652 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2653 assert_eq!(node_txn[0].input.len(), 1);
2654 check_spends!(node_txn[0], chan_1.3);
2655 assert_eq!(node_txn[1].input.len(), 1);
2656 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2657 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2658 check_spends!(node_txn[1], node_txn[0]);
2660 // Filter out any non justice transactions.
2661 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2662 assert!(node_txn.len() > 3);
2664 assert_eq!(node_txn[0].input.len(), 1);
2665 assert_eq!(node_txn[1].input.len(), 1);
2666 assert_eq!(node_txn[2].input.len(), 1);
2668 check_spends!(node_txn[0], revoked_local_txn[0]);
2669 check_spends!(node_txn[1], revoked_local_txn[0]);
2670 check_spends!(node_txn[2], revoked_local_txn[0]);
2672 let mut witness_lens = BTreeSet::new();
2673 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2674 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2675 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2676 assert_eq!(witness_lens.len(), 3);
2677 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2678 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2679 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2681 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2682 // ANTI_REORG_DELAY confirmations.
2683 mine_transaction(&nodes[1], &node_txn[0]);
2684 mine_transaction(&nodes[1], &node_txn[1]);
2685 mine_transaction(&nodes[1], &node_txn[2]);
2686 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2687 expect_payment_failed!(nodes[1], payment_hash_2, false);
2689 get_announce_close_broadcast_events(&nodes, 0, 1);
2690 assert_eq!(nodes[0].node.list_channels().len(), 0);
2691 assert_eq!(nodes[1].node.list_channels().len(), 0);
2695 fn test_htlc_on_chain_success() {
2696 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2697 // the preimage backward accordingly. So here we test that ChannelManager is
2698 // broadcasting the right event to other nodes in payment path.
2699 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2700 // A --------------------> B ----------------------> C (preimage)
2701 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2702 // commitment transaction was broadcast.
2703 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2705 // B should be able to claim via preimage if A then broadcasts its local tx.
2706 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2707 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2708 // PaymentSent event).
2710 let chanmon_cfgs = create_chanmon_cfgs(3);
2711 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2712 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2713 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2715 // Create some initial channels
2716 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2717 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2719 // Ensure all nodes are at the same height
2720 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2721 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2722 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2723 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2725 // Rebalance the network a bit by relaying one payment through all the channels...
2726 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2727 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2729 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2730 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2732 // Broadcast legit commitment tx from C on B's chain
2733 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2734 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2735 assert_eq!(commitment_tx.len(), 1);
2736 check_spends!(commitment_tx[0], chan_2.3);
2737 nodes[2].node.claim_funds(our_payment_preimage);
2738 expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2739 nodes[2].node.claim_funds(our_payment_preimage_2);
2740 expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2741 check_added_monitors!(nodes[2], 2);
2742 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2743 assert!(updates.update_add_htlcs.is_empty());
2744 assert!(updates.update_fail_htlcs.is_empty());
2745 assert!(updates.update_fail_malformed_htlcs.is_empty());
2746 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2748 mine_transaction(&nodes[2], &commitment_tx[0]);
2749 check_closed_broadcast!(nodes[2], true);
2750 check_added_monitors!(nodes[2], 1);
2751 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2752 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2753 assert_eq!(node_txn.len(), 2);
2754 check_spends!(node_txn[0], commitment_tx[0]);
2755 check_spends!(node_txn[1], commitment_tx[0]);
2756 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2757 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2758 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2759 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2760 assert_eq!(node_txn[0].lock_time.0, 0);
2761 assert_eq!(node_txn[1].lock_time.0, 0);
2763 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2764 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()]));
2765 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2767 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2768 assert_eq!(added_monitors.len(), 1);
2769 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2770 added_monitors.clear();
2772 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2773 assert_eq!(forwarded_events.len(), 3);
2774 match forwarded_events[0] {
2775 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2776 _ => panic!("Unexpected event"),
2778 let chan_id = Some(chan_1.2);
2779 match forwarded_events[1] {
2780 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2781 assert_eq!(fee_earned_msat, Some(1000));
2782 assert_eq!(prev_channel_id, chan_id);
2783 assert_eq!(claim_from_onchain_tx, true);
2784 assert_eq!(next_channel_id, Some(chan_2.2));
2785 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2789 match forwarded_events[2] {
2790 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2791 assert_eq!(fee_earned_msat, Some(1000));
2792 assert_eq!(prev_channel_id, chan_id);
2793 assert_eq!(claim_from_onchain_tx, true);
2794 assert_eq!(next_channel_id, Some(chan_2.2));
2795 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2799 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2801 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2802 assert_eq!(added_monitors.len(), 2);
2803 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2804 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2805 added_monitors.clear();
2807 assert_eq!(events.len(), 3);
2809 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2810 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2812 match nodes_2_event {
2813 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2814 _ => panic!("Unexpected event"),
2817 match nodes_0_event {
2818 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, .. } } => {
2819 assert!(update_add_htlcs.is_empty());
2820 assert!(update_fail_htlcs.is_empty());
2821 assert_eq!(update_fulfill_htlcs.len(), 1);
2822 assert!(update_fail_malformed_htlcs.is_empty());
2823 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2825 _ => panic!("Unexpected event"),
2828 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2830 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2831 _ => panic!("Unexpected event"),
2834 macro_rules! check_tx_local_broadcast {
2835 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2836 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2837 assert_eq!(node_txn.len(), 2);
2838 // Node[1]: 2 * HTLC-timeout tx
2839 // Node[0]: 2 * HTLC-timeout tx
2840 check_spends!(node_txn[0], $commitment_tx);
2841 check_spends!(node_txn[1], $commitment_tx);
2842 assert_ne!(node_txn[0].lock_time.0, 0);
2843 assert_ne!(node_txn[1].lock_time.0, 0);
2845 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2846 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2847 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2848 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2850 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2851 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2852 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2853 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2858 // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2859 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2861 // Broadcast legit commitment tx from A on B's chain
2862 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2863 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2864 check_spends!(node_a_commitment_tx[0], chan_1.3);
2865 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2866 check_closed_broadcast!(nodes[1], true);
2867 check_added_monitors!(nodes[1], 1);
2868 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2869 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2870 assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2871 let commitment_spend =
2872 if node_txn.len() == 1 {
2875 // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2876 // FullBlockViaListen
2877 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2878 check_spends!(node_txn[1], commitment_tx[0]);
2879 check_spends!(node_txn[2], commitment_tx[0]);
2880 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2883 check_spends!(node_txn[0], commitment_tx[0]);
2884 check_spends!(node_txn[1], commitment_tx[0]);
2885 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2890 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2891 assert_eq!(commitment_spend.input.len(), 2);
2892 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2893 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2894 assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1);
2895 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2896 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2897 // we already checked the same situation with A.
2899 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2900 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
2901 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
2902 check_closed_broadcast!(nodes[0], true);
2903 check_added_monitors!(nodes[0], 1);
2904 let events = nodes[0].node.get_and_clear_pending_events();
2905 assert_eq!(events.len(), 5);
2906 let mut first_claimed = false;
2907 for event in events {
2909 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2910 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2911 assert!(!first_claimed);
2912 first_claimed = true;
2914 assert_eq!(payment_preimage, our_payment_preimage_2);
2915 assert_eq!(payment_hash, payment_hash_2);
2918 Event::PaymentPathSuccessful { .. } => {},
2919 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2920 _ => panic!("Unexpected event"),
2923 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
2926 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2927 // Test that in case of a unilateral close onchain, we detect the state of output and
2928 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2929 // broadcasting the right event to other nodes in payment path.
2930 // A ------------------> B ----------------------> C (timeout)
2931 // B's commitment tx C's commitment tx
2933 // B's HTLC timeout tx B's timeout tx
2935 let chanmon_cfgs = create_chanmon_cfgs(3);
2936 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2937 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2938 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2939 *nodes[0].connect_style.borrow_mut() = connect_style;
2940 *nodes[1].connect_style.borrow_mut() = connect_style;
2941 *nodes[2].connect_style.borrow_mut() = connect_style;
2943 // Create some intial channels
2944 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2945 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2947 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2948 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2949 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2951 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2953 // Broadcast legit commitment tx from C on B's chain
2954 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2955 check_spends!(commitment_tx[0], chan_2.3);
2956 nodes[2].node.fail_htlc_backwards(&payment_hash);
2957 check_added_monitors!(nodes[2], 0);
2958 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
2959 check_added_monitors!(nodes[2], 1);
2961 let events = nodes[2].node.get_and_clear_pending_msg_events();
2962 assert_eq!(events.len(), 1);
2964 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, .. } } => {
2965 assert!(update_add_htlcs.is_empty());
2966 assert!(!update_fail_htlcs.is_empty());
2967 assert!(update_fulfill_htlcs.is_empty());
2968 assert!(update_fail_malformed_htlcs.is_empty());
2969 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2971 _ => panic!("Unexpected event"),
2973 mine_transaction(&nodes[2], &commitment_tx[0]);
2974 check_closed_broadcast!(nodes[2], true);
2975 check_added_monitors!(nodes[2], 1);
2976 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2977 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2978 assert_eq!(node_txn.len(), 0);
2980 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2981 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2982 mine_transaction(&nodes[1], &commitment_tx[0]);
2983 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false);
2984 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2986 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
2987 if nodes[1].connect_style.borrow().skips_blocks() {
2988 assert_eq!(txn.len(), 1);
2990 assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
2992 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
2993 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2997 mine_transaction(&nodes[1], &timeout_tx);
2998 check_added_monitors!(nodes[1], 1);
2999 check_closed_broadcast!(nodes[1], true);
3001 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3003 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 }]);
3004 check_added_monitors!(nodes[1], 1);
3005 let events = nodes[1].node.get_and_clear_pending_msg_events();
3006 assert_eq!(events.len(), 1);
3008 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, .. } } => {
3009 assert!(update_add_htlcs.is_empty());
3010 assert!(!update_fail_htlcs.is_empty());
3011 assert!(update_fulfill_htlcs.is_empty());
3012 assert!(update_fail_malformed_htlcs.is_empty());
3013 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3015 _ => panic!("Unexpected event"),
3018 // Broadcast legit commitment tx from B on A's chain
3019 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3020 check_spends!(commitment_tx[0], chan_1.3);
3022 mine_transaction(&nodes[0], &commitment_tx[0]);
3023 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3025 check_closed_broadcast!(nodes[0], true);
3026 check_added_monitors!(nodes[0], 1);
3027 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
3028 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3029 assert_eq!(node_txn.len(), 1);
3030 check_spends!(node_txn[0], commitment_tx[0]);
3031 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3035 fn test_htlc_on_chain_timeout() {
3036 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3037 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3038 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3042 fn test_simple_commitment_revoked_fail_backward() {
3043 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3044 // and fail backward accordingly.
3046 let chanmon_cfgs = create_chanmon_cfgs(3);
3047 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3048 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3049 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3051 // Create some initial channels
3052 create_announced_chan_between_nodes(&nodes, 0, 1);
3053 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3055 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3056 // Get the will-be-revoked local txn from nodes[2]
3057 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3058 // Revoke the old state
3059 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3061 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3064 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3065 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3066 check_added_monitors!(nodes[1], 1);
3067 check_closed_broadcast!(nodes[1], true);
3069 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 }]);
3070 check_added_monitors!(nodes[1], 1);
3071 let events = nodes[1].node.get_and_clear_pending_msg_events();
3072 assert_eq!(events.len(), 1);
3074 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, .. } } => {
3075 assert!(update_add_htlcs.is_empty());
3076 assert_eq!(update_fail_htlcs.len(), 1);
3077 assert!(update_fulfill_htlcs.is_empty());
3078 assert!(update_fail_malformed_htlcs.is_empty());
3079 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3081 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3082 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3083 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3085 _ => panic!("Unexpected event"),
3089 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3090 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3091 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3092 // commitment transaction anymore.
3093 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3094 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3095 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3096 // technically disallowed and we should probably handle it reasonably.
3097 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3098 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3100 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3101 // commitment_signed (implying it will be in the latest remote commitment transaction).
3102 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3103 // and once they revoke the previous commitment transaction (allowing us to send a new
3104 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3105 let chanmon_cfgs = create_chanmon_cfgs(3);
3106 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3107 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3108 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3110 // Create some initial channels
3111 create_announced_chan_between_nodes(&nodes, 0, 1);
3112 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3114 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 });
3115 // Get the will-be-revoked local txn from nodes[2]
3116 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3117 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3118 // Revoke the old state
3119 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3121 let value = if use_dust {
3122 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3123 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3124 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3125 .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3128 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3129 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3132 nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3133 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3134 check_added_monitors!(nodes[2], 1);
3135 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3136 assert!(updates.update_add_htlcs.is_empty());
3137 assert!(updates.update_fulfill_htlcs.is_empty());
3138 assert!(updates.update_fail_malformed_htlcs.is_empty());
3139 assert_eq!(updates.update_fail_htlcs.len(), 1);
3140 assert!(updates.update_fee.is_none());
3141 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3142 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3143 // Drop the last RAA from 3 -> 2
3145 nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3146 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3147 check_added_monitors!(nodes[2], 1);
3148 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3149 assert!(updates.update_add_htlcs.is_empty());
3150 assert!(updates.update_fulfill_htlcs.is_empty());
3151 assert!(updates.update_fail_malformed_htlcs.is_empty());
3152 assert_eq!(updates.update_fail_htlcs.len(), 1);
3153 assert!(updates.update_fee.is_none());
3154 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3155 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3156 check_added_monitors!(nodes[1], 1);
3157 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3158 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3159 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3160 check_added_monitors!(nodes[2], 1);
3162 nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3163 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3164 check_added_monitors!(nodes[2], 1);
3165 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3166 assert!(updates.update_add_htlcs.is_empty());
3167 assert!(updates.update_fulfill_htlcs.is_empty());
3168 assert!(updates.update_fail_malformed_htlcs.is_empty());
3169 assert_eq!(updates.update_fail_htlcs.len(), 1);
3170 assert!(updates.update_fee.is_none());
3171 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3172 // At this point first_payment_hash has dropped out of the latest two commitment
3173 // transactions that nodes[1] is tracking...
3174 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3175 check_added_monitors!(nodes[1], 1);
3176 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3177 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3178 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3179 check_added_monitors!(nodes[2], 1);
3181 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3182 // on nodes[2]'s RAA.
3183 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3184 nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3185 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3186 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3187 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3188 check_added_monitors!(nodes[1], 0);
3191 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3192 // One monitor for the new revocation preimage, no second on as we won't generate a new
3193 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3194 check_added_monitors!(nodes[1], 1);
3195 let events = nodes[1].node.get_and_clear_pending_events();
3196 assert_eq!(events.len(), 2);
3198 Event::PendingHTLCsForwardable { .. } => { },
3199 _ => panic!("Unexpected event"),
3202 Event::HTLCHandlingFailed { .. } => { },
3203 _ => panic!("Unexpected event"),
3205 // Deliberately don't process the pending fail-back so they all fail back at once after
3206 // block connection just like the !deliver_bs_raa case
3209 let mut failed_htlcs = HashSet::new();
3210 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3212 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3213 check_added_monitors!(nodes[1], 1);
3214 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3216 let events = nodes[1].node.get_and_clear_pending_events();
3217 assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3219 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3220 _ => panic!("Unexepected event"),
3223 Event::PaymentPathFailed { ref payment_hash, .. } => {
3224 assert_eq!(*payment_hash, fourth_payment_hash);
3226 _ => panic!("Unexpected event"),
3229 Event::PaymentFailed { ref payment_hash, .. } => {
3230 assert_eq!(*payment_hash, fourth_payment_hash);
3232 _ => panic!("Unexpected event"),
3235 nodes[1].node.process_pending_htlc_forwards();
3236 check_added_monitors!(nodes[1], 1);
3238 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3239 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3242 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3243 match nodes_2_event {
3244 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, .. } } => {
3245 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3246 assert_eq!(update_add_htlcs.len(), 1);
3247 assert!(update_fulfill_htlcs.is_empty());
3248 assert!(update_fail_htlcs.is_empty());
3249 assert!(update_fail_malformed_htlcs.is_empty());
3251 _ => panic!("Unexpected event"),
3255 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3256 match nodes_2_event {
3257 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3258 assert_eq!(channel_id, chan_2.2);
3259 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3261 _ => panic!("Unexpected event"),
3264 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3265 match nodes_0_event {
3266 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, .. } } => {
3267 assert!(update_add_htlcs.is_empty());
3268 assert_eq!(update_fail_htlcs.len(), 3);
3269 assert!(update_fulfill_htlcs.is_empty());
3270 assert!(update_fail_malformed_htlcs.is_empty());
3271 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3273 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3274 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3275 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3277 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3279 let events = nodes[0].node.get_and_clear_pending_events();
3280 assert_eq!(events.len(), 6);
3282 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3283 assert!(failed_htlcs.insert(payment_hash.0));
3284 // If we delivered B's RAA we got an unknown preimage error, not something
3285 // that we should update our routing table for.
3286 if !deliver_bs_raa {
3287 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3290 _ => panic!("Unexpected event"),
3293 Event::PaymentFailed { ref payment_hash, .. } => {
3294 assert_eq!(*payment_hash, first_payment_hash);
3296 _ => panic!("Unexpected event"),
3299 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3300 assert!(failed_htlcs.insert(payment_hash.0));
3302 _ => panic!("Unexpected event"),
3305 Event::PaymentFailed { ref payment_hash, .. } => {
3306 assert_eq!(*payment_hash, second_payment_hash);
3308 _ => panic!("Unexpected event"),
3311 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3312 assert!(failed_htlcs.insert(payment_hash.0));
3314 _ => panic!("Unexpected event"),
3317 Event::PaymentFailed { ref payment_hash, .. } => {
3318 assert_eq!(*payment_hash, third_payment_hash);
3320 _ => panic!("Unexpected event"),
3323 _ => panic!("Unexpected event"),
3326 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3328 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3329 _ => panic!("Unexpected event"),
3332 assert!(failed_htlcs.contains(&first_payment_hash.0));
3333 assert!(failed_htlcs.contains(&second_payment_hash.0));
3334 assert!(failed_htlcs.contains(&third_payment_hash.0));
3338 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3339 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3340 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3341 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3342 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3346 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3347 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3348 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3349 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3350 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3354 fn fail_backward_pending_htlc_upon_channel_failure() {
3355 let chanmon_cfgs = create_chanmon_cfgs(2);
3356 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3357 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3358 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3359 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3361 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3363 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3364 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3365 PaymentId(payment_hash.0)).unwrap();
3366 check_added_monitors!(nodes[0], 1);
3368 let payment_event = {
3369 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3370 assert_eq!(events.len(), 1);
3371 SendEvent::from_event(events.remove(0))
3373 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3374 assert_eq!(payment_event.msgs.len(), 1);
3377 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3378 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3380 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3381 RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3382 check_added_monitors!(nodes[0], 0);
3384 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3387 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3389 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3391 let secp_ctx = Secp256k1::new();
3392 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3393 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3394 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3395 &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3396 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3397 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3399 // Send a 0-msat update_add_htlc to fail the channel.
3400 let update_add_htlc = msgs::UpdateAddHTLC {
3406 onion_routing_packet,
3408 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3410 let events = nodes[0].node.get_and_clear_pending_events();
3411 assert_eq!(events.len(), 3);
3412 // Check that Alice fails backward the pending HTLC from the second payment.
3414 Event::PaymentPathFailed { payment_hash, .. } => {
3415 assert_eq!(payment_hash, failed_payment_hash);
3417 _ => panic!("Unexpected event"),
3420 Event::PaymentFailed { payment_hash, .. } => {
3421 assert_eq!(payment_hash, failed_payment_hash);
3423 _ => panic!("Unexpected event"),
3426 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3427 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3429 _ => panic!("Unexpected event {:?}", events[1]),
3431 check_closed_broadcast!(nodes[0], true);
3432 check_added_monitors!(nodes[0], 1);
3436 fn test_htlc_ignore_latest_remote_commitment() {
3437 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3438 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3439 let chanmon_cfgs = create_chanmon_cfgs(2);
3440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3443 if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3444 // We rely on the ability to connect a block redundantly, which isn't allowed via
3445 // `chain::Listen`, so we never run the test if we randomly get assigned that
3449 create_announced_chan_between_nodes(&nodes, 0, 1);
3451 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3452 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3453 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3454 check_closed_broadcast!(nodes[0], true);
3455 check_added_monitors!(nodes[0], 1);
3456 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3458 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3459 assert_eq!(node_txn.len(), 3);
3460 assert_eq!(node_txn[0].txid(), node_txn[1].txid());
3462 let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[1].clone()]);
3463 connect_block(&nodes[1], &block);
3464 check_closed_broadcast!(nodes[1], true);
3465 check_added_monitors!(nodes[1], 1);
3466 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3468 // Duplicate the connect_block call since this may happen due to other listeners
3469 // registering new transactions
3470 connect_block(&nodes[1], &block);
3474 fn test_force_close_fail_back() {
3475 // Check which HTLCs are failed-backwards on channel force-closure
3476 let chanmon_cfgs = create_chanmon_cfgs(3);
3477 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3478 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3479 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3480 create_announced_chan_between_nodes(&nodes, 0, 1);
3481 create_announced_chan_between_nodes(&nodes, 1, 2);
3483 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3485 let mut payment_event = {
3486 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3487 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3488 check_added_monitors!(nodes[0], 1);
3490 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3491 assert_eq!(events.len(), 1);
3492 SendEvent::from_event(events.remove(0))
3495 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3496 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3498 expect_pending_htlcs_forwardable!(nodes[1]);
3500 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3501 assert_eq!(events_2.len(), 1);
3502 payment_event = SendEvent::from_event(events_2.remove(0));
3503 assert_eq!(payment_event.msgs.len(), 1);
3505 check_added_monitors!(nodes[1], 1);
3506 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3507 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3508 check_added_monitors!(nodes[2], 1);
3509 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3511 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3512 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3513 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3515 nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3516 check_closed_broadcast!(nodes[2], true);
3517 check_added_monitors!(nodes[2], 1);
3518 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3520 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3521 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3522 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3523 // back to nodes[1] upon timeout otherwise.
3524 assert_eq!(node_txn.len(), 1);
3528 mine_transaction(&nodes[1], &tx);
3530 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3531 check_closed_broadcast!(nodes[1], true);
3532 check_added_monitors!(nodes[1], 1);
3533 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3535 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3537 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3538 .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);
3540 mine_transaction(&nodes[2], &tx);
3541 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3542 assert_eq!(node_txn.len(), 1);
3543 assert_eq!(node_txn[0].input.len(), 1);
3544 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3545 assert_eq!(node_txn[0].lock_time.0, 0); // Must be an HTLC-Success
3546 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3548 check_spends!(node_txn[0], tx);
3552 fn test_dup_events_on_peer_disconnect() {
3553 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3554 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3555 // as we used to generate the event immediately upon receipt of the payment preimage in the
3556 // update_fulfill_htlc message.
3558 let chanmon_cfgs = create_chanmon_cfgs(2);
3559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3562 create_announced_chan_between_nodes(&nodes, 0, 1);
3564 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3566 nodes[1].node.claim_funds(payment_preimage);
3567 expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3568 check_added_monitors!(nodes[1], 1);
3569 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3570 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3571 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
3573 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3574 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3576 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3577 expect_payment_path_successful!(nodes[0]);
3581 fn test_peer_disconnected_before_funding_broadcasted() {
3582 // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3583 // before the funding transaction has been broadcasted.
3584 let chanmon_cfgs = create_chanmon_cfgs(2);
3585 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3586 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3587 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3589 // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3590 // broadcasted, even though it's created by `nodes[0]`.
3591 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();
3592 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3593 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3594 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3595 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3597 let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3598 assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3600 assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3602 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3603 assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3605 // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3606 // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3609 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3612 // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3613 // disconnected before the funding transaction was broadcasted.
3614 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3615 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3617 check_closed_event!(nodes[0], 1, ClosureReason::DisconnectedPeer);
3618 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
3622 fn test_simple_peer_disconnect() {
3623 // Test that we can reconnect when there are no lost messages
3624 let chanmon_cfgs = create_chanmon_cfgs(3);
3625 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3626 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3627 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3628 create_announced_chan_between_nodes(&nodes, 0, 1);
3629 create_announced_chan_between_nodes(&nodes, 1, 2);
3631 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3632 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3633 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3635 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3636 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3637 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3638 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
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], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3644 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3645 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3646 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3647 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).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());
3652 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3653 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3655 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3657 let events = nodes[0].node.get_and_clear_pending_events();
3658 assert_eq!(events.len(), 4);
3660 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3661 assert_eq!(payment_preimage, payment_preimage_3);
3662 assert_eq!(payment_hash, payment_hash_3);
3664 _ => panic!("Unexpected event"),
3667 Event::PaymentPathSuccessful { .. } => {},
3668 _ => panic!("Unexpected event"),
3671 Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3672 assert_eq!(payment_hash, payment_hash_5);
3673 assert!(payment_failed_permanently);
3675 _ => panic!("Unexpected event"),
3678 Event::PaymentFailed { payment_hash, .. } => {
3679 assert_eq!(payment_hash, payment_hash_5);
3681 _ => panic!("Unexpected event"),
3685 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3686 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3689 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3690 // Test that we can reconnect when in-flight HTLC updates get dropped
3691 let chanmon_cfgs = create_chanmon_cfgs(2);
3692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3694 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3696 let mut as_channel_ready = None;
3697 let channel_id = if messages_delivered == 0 {
3698 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3699 as_channel_ready = Some(channel_ready);
3700 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3701 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3702 // it before the channel_reestablish message.
3705 create_announced_chan_between_nodes(&nodes, 0, 1).2
3708 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3710 let payment_event = {
3711 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3712 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3713 check_added_monitors!(nodes[0], 1);
3715 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3716 assert_eq!(events.len(), 1);
3717 SendEvent::from_event(events.remove(0))
3719 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3721 if messages_delivered < 2 {
3722 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3724 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3725 if messages_delivered >= 3 {
3726 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3727 check_added_monitors!(nodes[1], 1);
3728 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3730 if messages_delivered >= 4 {
3731 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3732 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3733 check_added_monitors!(nodes[0], 1);
3735 if messages_delivered >= 5 {
3736 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3737 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3738 // No commitment_signed so get_event_msg's assert(len == 1) passes
3739 check_added_monitors!(nodes[0], 1);
3741 if messages_delivered >= 6 {
3742 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3743 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3744 check_added_monitors!(nodes[1], 1);
3751 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3752 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3753 if messages_delivered < 3 {
3754 if simulate_broken_lnd {
3755 // lnd has a long-standing bug where they send a channel_ready prior to a
3756 // channel_reestablish if you reconnect prior to channel_ready time.
3758 // Here we simulate that behavior, delivering a channel_ready immediately on
3759 // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3760 // in `reconnect_nodes` but we currently don't fail based on that.
3762 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3763 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3765 // Even if the channel_ready messages get exchanged, as long as nothing further was
3766 // received on either side, both sides will need to resend them.
3767 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3768 } else if messages_delivered == 3 {
3769 // nodes[0] still wants its RAA + commitment_signed
3770 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3771 } else if messages_delivered == 4 {
3772 // nodes[0] still wants its commitment_signed
3773 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3774 } else if messages_delivered == 5 {
3775 // nodes[1] still wants its final RAA
3776 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3777 } else if messages_delivered == 6 {
3778 // Everything was delivered...
3779 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3782 let events_1 = nodes[1].node.get_and_clear_pending_events();
3783 if messages_delivered == 0 {
3784 assert_eq!(events_1.len(), 2);
3786 Event::ChannelReady { .. } => { },
3787 _ => panic!("Unexpected event"),
3790 Event::PendingHTLCsForwardable { .. } => { },
3791 _ => panic!("Unexpected event"),
3794 assert_eq!(events_1.len(), 1);
3796 Event::PendingHTLCsForwardable { .. } => { },
3797 _ => panic!("Unexpected event"),
3801 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3802 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3803 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3805 nodes[1].node.process_pending_htlc_forwards();
3807 let events_2 = nodes[1].node.get_and_clear_pending_events();
3808 assert_eq!(events_2.len(), 1);
3810 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3811 assert_eq!(payment_hash_1, *payment_hash);
3812 assert_eq!(amount_msat, 1_000_000);
3813 assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3814 assert_eq!(via_channel_id, Some(channel_id));
3816 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3817 assert!(payment_preimage.is_none());
3818 assert_eq!(payment_secret_1, *payment_secret);
3820 _ => panic!("expected PaymentPurpose::InvoicePayment")
3823 _ => panic!("Unexpected event"),
3826 nodes[1].node.claim_funds(payment_preimage_1);
3827 check_added_monitors!(nodes[1], 1);
3828 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3830 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3831 assert_eq!(events_3.len(), 1);
3832 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3833 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3834 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3835 assert!(updates.update_add_htlcs.is_empty());
3836 assert!(updates.update_fail_htlcs.is_empty());
3837 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3838 assert!(updates.update_fail_malformed_htlcs.is_empty());
3839 assert!(updates.update_fee.is_none());
3840 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3842 _ => panic!("Unexpected event"),
3845 if messages_delivered >= 1 {
3846 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3848 let events_4 = nodes[0].node.get_and_clear_pending_events();
3849 assert_eq!(events_4.len(), 1);
3851 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3852 assert_eq!(payment_preimage_1, *payment_preimage);
3853 assert_eq!(payment_hash_1, *payment_hash);
3855 _ => panic!("Unexpected event"),
3858 if messages_delivered >= 2 {
3859 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3860 check_added_monitors!(nodes[0], 1);
3861 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3863 if messages_delivered >= 3 {
3864 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3865 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3866 check_added_monitors!(nodes[1], 1);
3868 if messages_delivered >= 4 {
3869 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3870 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3871 // No commitment_signed so get_event_msg's assert(len == 1) passes
3872 check_added_monitors!(nodes[1], 1);
3874 if messages_delivered >= 5 {
3875 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3876 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3877 check_added_monitors!(nodes[0], 1);
3884 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3885 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3886 if messages_delivered < 2 {
3887 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3888 if messages_delivered < 1 {
3889 expect_payment_sent!(nodes[0], payment_preimage_1);
3891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3893 } else if messages_delivered == 2 {
3894 // nodes[0] still wants its RAA + commitment_signed
3895 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3896 } else if messages_delivered == 3 {
3897 // nodes[0] still wants its commitment_signed
3898 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3899 } else if messages_delivered == 4 {
3900 // nodes[1] still wants its final RAA
3901 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3902 } else if messages_delivered == 5 {
3903 // Everything was delivered...
3904 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3907 if messages_delivered == 1 || messages_delivered == 2 {
3908 expect_payment_path_successful!(nodes[0]);
3910 if messages_delivered <= 5 {
3911 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3912 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3914 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3916 if messages_delivered > 2 {
3917 expect_payment_path_successful!(nodes[0]);
3920 // Channel should still work fine...
3921 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3922 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3923 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3927 fn test_drop_messages_peer_disconnect_a() {
3928 do_test_drop_messages_peer_disconnect(0, true);
3929 do_test_drop_messages_peer_disconnect(0, false);
3930 do_test_drop_messages_peer_disconnect(1, false);
3931 do_test_drop_messages_peer_disconnect(2, false);
3935 fn test_drop_messages_peer_disconnect_b() {
3936 do_test_drop_messages_peer_disconnect(3, false);
3937 do_test_drop_messages_peer_disconnect(4, false);
3938 do_test_drop_messages_peer_disconnect(5, false);
3939 do_test_drop_messages_peer_disconnect(6, false);
3943 fn test_channel_ready_without_best_block_updated() {
3944 // Previously, if we were offline when a funding transaction was locked in, and then we came
3945 // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
3946 // generate a channel_ready until a later best_block_updated. This tests that we generate the
3947 // channel_ready immediately instead.
3948 let chanmon_cfgs = create_chanmon_cfgs(2);
3949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3951 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3952 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
3954 let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
3956 let conf_height = nodes[0].best_block_info().1 + 1;
3957 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
3958 let block_txn = [funding_tx];
3959 let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
3960 let conf_block_header = nodes[0].get_block_header(conf_height);
3961 nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
3963 // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
3964 let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
3965 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
3969 fn test_drop_messages_peer_disconnect_dual_htlc() {
3970 // Test that we can handle reconnecting when both sides of a channel have pending
3971 // commitment_updates when we disconnect.
3972 let chanmon_cfgs = create_chanmon_cfgs(2);
3973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3975 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3976 create_announced_chan_between_nodes(&nodes, 0, 1);
3978 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3980 // Now try to send a second payment which will fail to send
3981 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3982 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
3983 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
3984 check_added_monitors!(nodes[0], 1);
3986 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3987 assert_eq!(events_1.len(), 1);
3989 MessageSendEvent::UpdateHTLCs { .. } => {},
3990 _ => panic!("Unexpected event"),
3993 nodes[1].node.claim_funds(payment_preimage_1);
3994 expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3995 check_added_monitors!(nodes[1], 1);
3997 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3998 assert_eq!(events_2.len(), 1);
4000 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 } } => {
4001 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4002 assert!(update_add_htlcs.is_empty());
4003 assert_eq!(update_fulfill_htlcs.len(), 1);
4004 assert!(update_fail_htlcs.is_empty());
4005 assert!(update_fail_malformed_htlcs.is_empty());
4006 assert!(update_fee.is_none());
4008 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4009 let events_3 = nodes[0].node.get_and_clear_pending_events();
4010 assert_eq!(events_3.len(), 1);
4012 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4013 assert_eq!(*payment_preimage, payment_preimage_1);
4014 assert_eq!(*payment_hash, payment_hash_1);
4016 _ => panic!("Unexpected event"),
4019 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4020 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4021 // No commitment_signed so get_event_msg's assert(len == 1) passes
4022 check_added_monitors!(nodes[0], 1);
4024 _ => panic!("Unexpected event"),
4027 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4030 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();
4031 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4032 assert_eq!(reestablish_1.len(), 1);
4033 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();
4034 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4035 assert_eq!(reestablish_2.len(), 1);
4037 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4038 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4039 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4040 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4042 assert!(as_resp.0.is_none());
4043 assert!(bs_resp.0.is_none());
4045 assert!(bs_resp.1.is_none());
4046 assert!(bs_resp.2.is_none());
4048 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4050 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4051 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4052 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4053 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4054 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4055 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4056 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4057 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4058 // No commitment_signed so get_event_msg's assert(len == 1) passes
4059 check_added_monitors!(nodes[1], 1);
4061 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4062 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4063 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4064 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4065 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4066 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4067 assert!(bs_second_commitment_signed.update_fee.is_none());
4068 check_added_monitors!(nodes[1], 1);
4070 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4071 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4072 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4073 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4074 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4075 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4076 assert!(as_commitment_signed.update_fee.is_none());
4077 check_added_monitors!(nodes[0], 1);
4079 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4080 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4081 // No commitment_signed so get_event_msg's assert(len == 1) passes
4082 check_added_monitors!(nodes[0], 1);
4084 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4085 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4086 // No commitment_signed so get_event_msg's assert(len == 1) passes
4087 check_added_monitors!(nodes[1], 1);
4089 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4090 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4091 check_added_monitors!(nodes[1], 1);
4093 expect_pending_htlcs_forwardable!(nodes[1]);
4095 let events_5 = nodes[1].node.get_and_clear_pending_events();
4096 assert_eq!(events_5.len(), 1);
4098 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4099 assert_eq!(payment_hash_2, *payment_hash);
4101 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4102 assert!(payment_preimage.is_none());
4103 assert_eq!(payment_secret_2, *payment_secret);
4105 _ => panic!("expected PaymentPurpose::InvoicePayment")
4108 _ => panic!("Unexpected event"),
4111 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4112 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4113 check_added_monitors!(nodes[0], 1);
4115 expect_payment_path_successful!(nodes[0]);
4116 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4119 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4120 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4121 // to avoid our counterparty failing the channel.
4122 let chanmon_cfgs = create_chanmon_cfgs(2);
4123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4127 create_announced_chan_between_nodes(&nodes, 0, 1);
4129 let our_payment_hash = if send_partial_mpp {
4130 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4131 // Use the utility function send_payment_along_path to send the payment with MPP data which
4132 // indicates there are more HTLCs coming.
4133 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.
4134 let payment_id = PaymentId([42; 32]);
4135 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4136 RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4137 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4138 RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4139 &None, session_privs[0]).unwrap();
4140 check_added_monitors!(nodes[0], 1);
4141 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4142 assert_eq!(events.len(), 1);
4143 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4144 // hop should *not* yet generate any PaymentClaimable event(s).
4145 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4148 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4151 let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4152 connect_block(&nodes[0], &block);
4153 connect_block(&nodes[1], &block);
4154 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4155 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4156 block.header.prev_blockhash = block.block_hash();
4157 connect_block(&nodes[0], &block);
4158 connect_block(&nodes[1], &block);
4161 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4163 check_added_monitors!(nodes[1], 1);
4164 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4165 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4166 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4167 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4168 assert!(htlc_timeout_updates.update_fee.is_none());
4170 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4171 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4172 // 100_000 msat as u64, followed by the height at which we failed back above
4173 let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4174 expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4175 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4179 fn test_htlc_timeout() {
4180 do_test_htlc_timeout(true);
4181 do_test_htlc_timeout(false);
4184 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4185 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4186 let chanmon_cfgs = create_chanmon_cfgs(3);
4187 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4188 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4189 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4190 create_announced_chan_between_nodes(&nodes, 0, 1);
4191 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4193 // Make sure all nodes are at the same starting height
4194 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4195 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4196 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4198 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4199 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4200 nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4201 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4202 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4203 check_added_monitors!(nodes[1], 1);
4205 // Now attempt to route a second payment, which should be placed in the holding cell
4206 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4207 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4208 sending_node.node.send_payment_with_route(&route, second_payment_hash,
4209 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4211 check_added_monitors!(nodes[0], 1);
4212 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4213 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4214 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4215 expect_pending_htlcs_forwardable!(nodes[1]);
4217 check_added_monitors!(nodes[1], 0);
4219 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4220 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4221 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4222 connect_blocks(&nodes[1], 1);
4225 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 }]);
4226 check_added_monitors!(nodes[1], 1);
4227 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4228 assert_eq!(fail_commit.len(), 1);
4229 match fail_commit[0] {
4230 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4231 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4232 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4234 _ => unreachable!(),
4236 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4238 expect_payment_failed!(nodes[1], second_payment_hash, false);
4243 fn test_holding_cell_htlc_add_timeouts() {
4244 do_test_holding_cell_htlc_add_timeouts(false);
4245 do_test_holding_cell_htlc_add_timeouts(true);
4248 macro_rules! check_spendable_outputs {
4249 ($node: expr, $keysinterface: expr) => {
4251 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4252 let mut txn = Vec::new();
4253 let mut all_outputs = Vec::new();
4254 let secp_ctx = Secp256k1::new();
4255 for event in events.drain(..) {
4257 Event::SpendableOutputs { mut outputs } => {
4258 for outp in outputs.drain(..) {
4259 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());
4260 all_outputs.push(outp);
4263 _ => panic!("Unexpected event"),
4266 if all_outputs.len() > 1 {
4267 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) {
4277 fn test_claim_sizeable_push_msat() {
4278 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4279 let chanmon_cfgs = create_chanmon_cfgs(2);
4280 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4281 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4282 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4284 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4285 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4286 check_closed_broadcast!(nodes[1], true);
4287 check_added_monitors!(nodes[1], 1);
4288 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4289 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4290 assert_eq!(node_txn.len(), 1);
4291 check_spends!(node_txn[0], chan.3);
4292 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
4294 mine_transaction(&nodes[1], &node_txn[0]);
4295 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4297 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4298 assert_eq!(spend_txn.len(), 1);
4299 assert_eq!(spend_txn[0].input.len(), 1);
4300 check_spends!(spend_txn[0], node_txn[0]);
4301 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4305 fn test_claim_on_remote_sizeable_push_msat() {
4306 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4307 // to_remote output is encumbered by a P2WPKH
4308 let chanmon_cfgs = create_chanmon_cfgs(2);
4309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4311 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4313 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4314 nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4315 check_closed_broadcast!(nodes[0], true);
4316 check_added_monitors!(nodes[0], 1);
4317 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4319 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4320 assert_eq!(node_txn.len(), 1);
4321 check_spends!(node_txn[0], chan.3);
4322 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
4324 mine_transaction(&nodes[1], &node_txn[0]);
4325 check_closed_broadcast!(nodes[1], true);
4326 check_added_monitors!(nodes[1], 1);
4327 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4328 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4330 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4331 assert_eq!(spend_txn.len(), 1);
4332 check_spends!(spend_txn[0], node_txn[0]);
4336 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4337 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4338 // to_remote output is encumbered by a P2WPKH
4340 let chanmon_cfgs = create_chanmon_cfgs(2);
4341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4343 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4345 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4346 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4347 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4348 assert_eq!(revoked_local_txn[0].input.len(), 1);
4349 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4351 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4352 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4353 check_closed_broadcast!(nodes[1], true);
4354 check_added_monitors!(nodes[1], 1);
4355 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4357 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4358 mine_transaction(&nodes[1], &node_txn[0]);
4359 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4361 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4362 assert_eq!(spend_txn.len(), 3);
4363 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4364 check_spends!(spend_txn[1], node_txn[0]);
4365 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4369 fn test_static_spendable_outputs_preimage_tx() {
4370 let chanmon_cfgs = create_chanmon_cfgs(2);
4371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4373 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4375 // Create some initial channels
4376 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4378 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4380 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4381 assert_eq!(commitment_tx[0].input.len(), 1);
4382 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4384 // Settle A's commitment tx on B's chain
4385 nodes[1].node.claim_funds(payment_preimage);
4386 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4387 check_added_monitors!(nodes[1], 1);
4388 mine_transaction(&nodes[1], &commitment_tx[0]);
4389 check_added_monitors!(nodes[1], 1);
4390 let events = nodes[1].node.get_and_clear_pending_msg_events();
4392 MessageSendEvent::UpdateHTLCs { .. } => {},
4393 _ => panic!("Unexpected event"),
4396 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4397 _ => panic!("Unexepected event"),
4400 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4401 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4402 assert_eq!(node_txn.len(), 1);
4403 check_spends!(node_txn[0], commitment_tx[0]);
4404 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4406 mine_transaction(&nodes[1], &node_txn[0]);
4407 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4408 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4410 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4411 assert_eq!(spend_txn.len(), 1);
4412 check_spends!(spend_txn[0], node_txn[0]);
4416 fn test_static_spendable_outputs_timeout_tx() {
4417 let chanmon_cfgs = create_chanmon_cfgs(2);
4418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4420 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4422 // Create some initial channels
4423 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4425 // Rebalance the network a bit by relaying one payment through all the channels ...
4426 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4428 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4430 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4431 assert_eq!(commitment_tx[0].input.len(), 1);
4432 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4434 // Settle A's commitment tx on B' chain
4435 mine_transaction(&nodes[1], &commitment_tx[0]);
4436 check_added_monitors!(nodes[1], 1);
4437 let events = nodes[1].node.get_and_clear_pending_msg_events();
4439 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4440 _ => panic!("Unexpected event"),
4442 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4444 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4445 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4446 assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4447 check_spends!(node_txn[0], commitment_tx[0].clone());
4448 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4450 mine_transaction(&nodes[1], &node_txn[0]);
4451 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4452 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4453 expect_payment_failed!(nodes[1], our_payment_hash, false);
4455 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4456 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4457 check_spends!(spend_txn[0], commitment_tx[0]);
4458 check_spends!(spend_txn[1], node_txn[0]);
4459 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4463 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4464 let chanmon_cfgs = create_chanmon_cfgs(2);
4465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4467 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4469 // Create some initial channels
4470 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4472 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4473 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4474 assert_eq!(revoked_local_txn[0].input.len(), 1);
4475 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4477 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4479 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4480 check_closed_broadcast!(nodes[1], true);
4481 check_added_monitors!(nodes[1], 1);
4482 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4484 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4485 assert_eq!(node_txn.len(), 1);
4486 assert_eq!(node_txn[0].input.len(), 2);
4487 check_spends!(node_txn[0], revoked_local_txn[0]);
4489 mine_transaction(&nodes[1], &node_txn[0]);
4490 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4492 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4493 assert_eq!(spend_txn.len(), 1);
4494 check_spends!(spend_txn[0], node_txn[0]);
4498 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4499 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4500 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4503 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4505 // Create some initial channels
4506 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4508 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4509 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4510 assert_eq!(revoked_local_txn[0].input.len(), 1);
4511 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4513 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4515 // A will generate HTLC-Timeout from revoked commitment tx
4516 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4517 check_closed_broadcast!(nodes[0], true);
4518 check_added_monitors!(nodes[0], 1);
4519 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4520 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4522 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4523 assert_eq!(revoked_htlc_txn.len(), 1);
4524 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4525 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4526 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4527 assert_ne!(revoked_htlc_txn[0].lock_time.0, 0); // HTLC-Timeout
4529 // B will generate justice tx from A's revoked commitment/HTLC tx
4530 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4531 check_closed_broadcast!(nodes[1], true);
4532 check_added_monitors!(nodes[1], 1);
4533 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4535 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4536 assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4537 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4538 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4539 // transactions next...
4540 assert_eq!(node_txn[0].input.len(), 3);
4541 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4543 assert_eq!(node_txn[1].input.len(), 2);
4544 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4545 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4546 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4548 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4549 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4552 mine_transaction(&nodes[1], &node_txn[1]);
4553 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4555 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4556 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4557 assert_eq!(spend_txn.len(), 1);
4558 assert_eq!(spend_txn[0].input.len(), 1);
4559 check_spends!(spend_txn[0], node_txn[1]);
4563 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4564 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4565 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4568 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4570 // Create some initial channels
4571 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4573 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4574 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4575 assert_eq!(revoked_local_txn[0].input.len(), 1);
4576 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4578 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4579 assert_eq!(revoked_local_txn[0].output.len(), 2);
4581 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4583 // B will generate HTLC-Success from revoked commitment tx
4584 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4585 check_closed_broadcast!(nodes[1], true);
4586 check_added_monitors!(nodes[1], 1);
4587 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4588 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4590 assert_eq!(revoked_htlc_txn.len(), 1);
4591 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4592 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4593 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4595 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4596 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4597 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4599 // A will generate justice tx from B's revoked commitment/HTLC tx
4600 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4601 check_closed_broadcast!(nodes[0], true);
4602 check_added_monitors!(nodes[0], 1);
4603 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4605 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4606 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4608 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4609 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4610 // transactions next...
4611 assert_eq!(node_txn[0].input.len(), 2);
4612 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4613 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4614 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4616 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4617 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4620 assert_eq!(node_txn[1].input.len(), 1);
4621 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4623 mine_transaction(&nodes[0], &node_txn[1]);
4624 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4626 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4627 // didn't try to generate any new transactions.
4629 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4630 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4631 assert_eq!(spend_txn.len(), 3);
4632 assert_eq!(spend_txn[0].input.len(), 1);
4633 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4634 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4635 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4636 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4640 fn test_onchain_to_onchain_claim() {
4641 // Test that in case of channel closure, we detect the state of output and claim HTLC
4642 // on downstream peer's remote commitment tx.
4643 // First, have C claim an HTLC against its own latest commitment transaction.
4644 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4646 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4649 let chanmon_cfgs = create_chanmon_cfgs(3);
4650 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4651 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4652 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4654 // Create some initial channels
4655 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4656 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4658 // Ensure all nodes are at the same height
4659 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4660 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4661 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4662 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4664 // Rebalance the network a bit by relaying one payment through all the channels ...
4665 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4666 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4668 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4669 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4670 check_spends!(commitment_tx[0], chan_2.3);
4671 nodes[2].node.claim_funds(payment_preimage);
4672 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4673 check_added_monitors!(nodes[2], 1);
4674 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4675 assert!(updates.update_add_htlcs.is_empty());
4676 assert!(updates.update_fail_htlcs.is_empty());
4677 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4678 assert!(updates.update_fail_malformed_htlcs.is_empty());
4680 mine_transaction(&nodes[2], &commitment_tx[0]);
4681 check_closed_broadcast!(nodes[2], true);
4682 check_added_monitors!(nodes[2], 1);
4683 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4685 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4686 assert_eq!(c_txn.len(), 1);
4687 check_spends!(c_txn[0], commitment_tx[0]);
4688 assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4689 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4690 assert_eq!(c_txn[0].lock_time.0, 0); // Success tx
4692 // 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
4693 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4694 check_added_monitors!(nodes[1], 1);
4695 let events = nodes[1].node.get_and_clear_pending_events();
4696 assert_eq!(events.len(), 2);
4698 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4699 _ => panic!("Unexpected event"),
4702 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4703 assert_eq!(fee_earned_msat, Some(1000));
4704 assert_eq!(prev_channel_id, Some(chan_1.2));
4705 assert_eq!(claim_from_onchain_tx, true);
4706 assert_eq!(next_channel_id, Some(chan_2.2));
4707 assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4709 _ => panic!("Unexpected event"),
4711 check_added_monitors!(nodes[1], 1);
4712 let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4713 assert_eq!(msg_events.len(), 3);
4714 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4715 let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4717 match nodes_2_event {
4718 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4719 _ => panic!("Unexpected event"),
4722 match nodes_0_event {
4723 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, .. } } => {
4724 assert!(update_add_htlcs.is_empty());
4725 assert!(update_fail_htlcs.is_empty());
4726 assert_eq!(update_fulfill_htlcs.len(), 1);
4727 assert!(update_fail_malformed_htlcs.is_empty());
4728 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4730 _ => panic!("Unexpected event"),
4733 // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4734 match msg_events[0] {
4735 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4736 _ => panic!("Unexpected event"),
4739 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4740 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4741 mine_transaction(&nodes[1], &commitment_tx[0]);
4742 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4743 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4744 // ChannelMonitor: HTLC-Success tx
4745 assert_eq!(b_txn.len(), 1);
4746 check_spends!(b_txn[0], commitment_tx[0]);
4747 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4748 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4749 assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1); // Success tx
4751 check_closed_broadcast!(nodes[1], true);
4752 check_added_monitors!(nodes[1], 1);
4756 fn test_duplicate_payment_hash_one_failure_one_success() {
4757 // Topology : A --> B --> C --> D
4758 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4759 // Note that because C will refuse to generate two payment secrets for the same payment hash,
4760 // we forward one of the payments onwards to D.
4761 let chanmon_cfgs = create_chanmon_cfgs(4);
4762 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4763 // When this test was written, the default base fee floated based on the HTLC count.
4764 // It is now fixed, so we simply set the fee to the expected value here.
4765 let mut config = test_default_channel_config();
4766 config.channel_config.forwarding_fee_base_msat = 196;
4767 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4768 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4769 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4771 create_announced_chan_between_nodes(&nodes, 0, 1);
4772 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4773 create_announced_chan_between_nodes(&nodes, 2, 3);
4775 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4776 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4777 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4778 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4779 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4781 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4783 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4784 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4785 // script push size limit so that the below script length checks match
4786 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
4787 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
4788 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
4789 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
4790 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
4792 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4793 assert_eq!(commitment_txn[0].input.len(), 1);
4794 check_spends!(commitment_txn[0], chan_2.3);
4796 mine_transaction(&nodes[1], &commitment_txn[0]);
4797 check_closed_broadcast!(nodes[1], true);
4798 check_added_monitors!(nodes[1], 1);
4799 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4800 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
4802 let htlc_timeout_tx;
4803 { // Extract one of the two HTLC-Timeout transaction
4804 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4805 // ChannelMonitor: timeout tx * 2-or-3
4806 assert!(node_txn.len() == 2 || node_txn.len() == 3);
4808 check_spends!(node_txn[0], commitment_txn[0]);
4809 assert_eq!(node_txn[0].input.len(), 1);
4810 assert_eq!(node_txn[0].output.len(), 1);
4812 if node_txn.len() > 2 {
4813 check_spends!(node_txn[1], commitment_txn[0]);
4814 assert_eq!(node_txn[1].input.len(), 1);
4815 assert_eq!(node_txn[1].output.len(), 1);
4816 assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4818 check_spends!(node_txn[2], commitment_txn[0]);
4819 assert_eq!(node_txn[2].input.len(), 1);
4820 assert_eq!(node_txn[2].output.len(), 1);
4821 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
4823 check_spends!(node_txn[1], commitment_txn[0]);
4824 assert_eq!(node_txn[1].input.len(), 1);
4825 assert_eq!(node_txn[1].output.len(), 1);
4826 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
4829 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4830 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4831 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
4832 // (with value 900 sats) will be claimed in the below `claim_funds` call.
4833 if node_txn.len() > 2 {
4834 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4835 htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
4837 htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
4841 nodes[2].node.claim_funds(our_payment_preimage);
4842 expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
4844 mine_transaction(&nodes[2], &commitment_txn[0]);
4845 check_added_monitors!(nodes[2], 2);
4846 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4847 let events = nodes[2].node.get_and_clear_pending_msg_events();
4849 MessageSendEvent::UpdateHTLCs { .. } => {},
4850 _ => panic!("Unexpected event"),
4853 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4854 _ => panic!("Unexepected event"),
4856 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4857 assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
4858 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4859 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4860 assert_eq!(htlc_success_txn[0].input.len(), 1);
4861 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4862 assert_eq!(htlc_success_txn[1].input.len(), 1);
4863 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4864 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
4865 assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
4867 mine_transaction(&nodes[1], &htlc_timeout_tx);
4868 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4869 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 }]);
4870 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4871 assert!(htlc_updates.update_add_htlcs.is_empty());
4872 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4873 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
4874 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4875 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4876 check_added_monitors!(nodes[1], 1);
4878 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4879 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4881 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4883 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
4885 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4886 mine_transaction(&nodes[1], &htlc_success_txn[1]);
4887 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
4888 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4889 assert!(updates.update_add_htlcs.is_empty());
4890 assert!(updates.update_fail_htlcs.is_empty());
4891 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4892 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
4893 assert!(updates.update_fail_malformed_htlcs.is_empty());
4894 check_added_monitors!(nodes[1], 1);
4896 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4897 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4898 expect_payment_sent(&nodes[0], our_payment_preimage, None, true);
4902 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4903 let chanmon_cfgs = create_chanmon_cfgs(2);
4904 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4905 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4906 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4908 // Create some initial channels
4909 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4911 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
4912 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4913 assert_eq!(local_txn.len(), 1);
4914 assert_eq!(local_txn[0].input.len(), 1);
4915 check_spends!(local_txn[0], chan_1.3);
4917 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4918 nodes[1].node.claim_funds(payment_preimage);
4919 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
4920 check_added_monitors!(nodes[1], 1);
4922 mine_transaction(&nodes[1], &local_txn[0]);
4923 check_added_monitors!(nodes[1], 1);
4924 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4925 let events = nodes[1].node.get_and_clear_pending_msg_events();
4927 MessageSendEvent::UpdateHTLCs { .. } => {},
4928 _ => panic!("Unexpected event"),
4931 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4932 _ => panic!("Unexepected event"),
4935 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4936 assert_eq!(node_txn.len(), 1);
4937 assert_eq!(node_txn[0].input.len(), 1);
4938 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4939 check_spends!(node_txn[0], local_txn[0]);
4943 mine_transaction(&nodes[1], &node_tx);
4944 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4946 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4947 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4948 assert_eq!(spend_txn.len(), 1);
4949 assert_eq!(spend_txn[0].input.len(), 1);
4950 check_spends!(spend_txn[0], node_tx);
4951 assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4954 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4955 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4956 // unrevoked commitment transaction.
4957 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4958 // a remote RAA before they could be failed backwards (and combinations thereof).
4959 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4960 // use the same payment hashes.
4961 // Thus, we use a six-node network:
4966 // And test where C fails back to A/B when D announces its latest commitment transaction
4967 let chanmon_cfgs = create_chanmon_cfgs(6);
4968 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4969 // When this test was written, the default base fee floated based on the HTLC count.
4970 // It is now fixed, so we simply set the fee to the expected value here.
4971 let mut config = test_default_channel_config();
4972 config.channel_config.forwarding_fee_base_msat = 196;
4973 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
4974 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4975 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4977 let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
4978 let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4979 let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
4980 let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
4981 let chan_3_5 = create_announced_chan_between_nodes(&nodes, 3, 5);
4983 // Rebalance and check output sanity...
4984 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4985 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4986 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
4988 let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
4989 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().holder_dust_limit_satoshis;
4991 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
4993 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
4994 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
4996 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
4998 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
5000 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5002 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5003 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5005 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());
5007 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());
5010 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5012 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5013 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
5016 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
5018 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5019 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());
5021 // Double-check that six of the new HTLC were added
5022 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5023 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5024 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5025 assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5027 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5028 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5029 nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5030 nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5031 nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5032 nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5033 check_added_monitors!(nodes[4], 0);
5035 let failed_destinations = vec![
5036 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5037 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5038 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5039 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5041 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5042 check_added_monitors!(nodes[4], 1);
5044 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5045 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5046 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5047 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5048 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5049 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5051 // Fail 3rd below-dust and 7th above-dust HTLCs
5052 nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5053 nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5054 check_added_monitors!(nodes[5], 0);
5056 let failed_destinations_2 = vec![
5057 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5058 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5060 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5061 check_added_monitors!(nodes[5], 1);
5063 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5064 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5065 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5066 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5068 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5070 // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5071 let failed_destinations_3 = vec![
5072 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5073 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5074 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5075 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5076 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5077 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5079 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5080 check_added_monitors!(nodes[3], 1);
5081 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5082 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5083 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5084 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5085 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5086 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5087 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5088 if deliver_last_raa {
5089 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5091 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5094 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5095 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5096 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5097 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5099 // We now broadcast the latest commitment transaction, which *should* result in failures for
5100 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5101 // the non-broadcast above-dust HTLCs.
5103 // Alternatively, we may broadcast the previous commitment transaction, which should only
5104 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5105 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5107 if announce_latest {
5108 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5110 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5112 let events = nodes[2].node.get_and_clear_pending_events();
5113 let close_event = if deliver_last_raa {
5114 assert_eq!(events.len(), 2 + 6);
5115 events.last().clone().unwrap()
5117 assert_eq!(events.len(), 1);
5118 events.last().clone().unwrap()
5121 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5122 _ => panic!("Unexpected event"),
5125 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5126 check_closed_broadcast!(nodes[2], true);
5127 if deliver_last_raa {
5128 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5130 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();
5131 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5133 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5134 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5136 repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5139 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5141 check_added_monitors!(nodes[2], 3);
5143 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5144 assert_eq!(cs_msgs.len(), 2);
5145 let mut a_done = false;
5146 for msg in cs_msgs {
5148 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5149 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5150 // should be failed-backwards here.
5151 let target = if *node_id == nodes[0].node.get_our_node_id() {
5152 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5153 for htlc in &updates.update_fail_htlcs {
5154 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 });
5156 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5161 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5162 for htlc in &updates.update_fail_htlcs {
5163 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5165 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5166 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5169 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5170 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5171 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5172 if announce_latest {
5173 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5174 if *node_id == nodes[0].node.get_our_node_id() {
5175 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5178 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5180 _ => panic!("Unexpected event"),
5184 let as_events = nodes[0].node.get_and_clear_pending_events();
5185 assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5186 let mut as_failds = HashSet::new();
5187 let mut as_updates = 0;
5188 for event in as_events.iter() {
5189 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5190 assert!(as_failds.insert(*payment_hash));
5191 if *payment_hash != payment_hash_2 {
5192 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5194 assert!(!payment_failed_permanently);
5196 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5199 } else if let &Event::PaymentFailed { .. } = event {
5200 } else { panic!("Unexpected event"); }
5202 assert!(as_failds.contains(&payment_hash_1));
5203 assert!(as_failds.contains(&payment_hash_2));
5204 if announce_latest {
5205 assert!(as_failds.contains(&payment_hash_3));
5206 assert!(as_failds.contains(&payment_hash_5));
5208 assert!(as_failds.contains(&payment_hash_6));
5210 let bs_events = nodes[1].node.get_and_clear_pending_events();
5211 assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5212 let mut bs_failds = HashSet::new();
5213 let mut bs_updates = 0;
5214 for event in bs_events.iter() {
5215 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5216 assert!(bs_failds.insert(*payment_hash));
5217 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5218 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5220 assert!(!payment_failed_permanently);
5222 if let PathFailure::OnPath { network_update: Some(_) } = failure {
5225 } else if let &Event::PaymentFailed { .. } = event {
5226 } else { panic!("Unexpected event"); }
5228 assert!(bs_failds.contains(&payment_hash_1));
5229 assert!(bs_failds.contains(&payment_hash_2));
5230 if announce_latest {
5231 assert!(bs_failds.contains(&payment_hash_4));
5233 assert!(bs_failds.contains(&payment_hash_5));
5235 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5236 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5237 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5238 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5239 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5240 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5244 fn test_fail_backwards_latest_remote_announce_a() {
5245 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5249 fn test_fail_backwards_latest_remote_announce_b() {
5250 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5254 fn test_fail_backwards_previous_remote_announce() {
5255 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5256 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5257 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5261 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5262 let chanmon_cfgs = create_chanmon_cfgs(2);
5263 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5264 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5265 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5267 // Create some initial channels
5268 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5270 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5271 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5272 assert_eq!(local_txn[0].input.len(), 1);
5273 check_spends!(local_txn[0], chan_1.3);
5275 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5276 mine_transaction(&nodes[0], &local_txn[0]);
5277 check_closed_broadcast!(nodes[0], true);
5278 check_added_monitors!(nodes[0], 1);
5279 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5280 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5282 let htlc_timeout = {
5283 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5284 assert_eq!(node_txn.len(), 1);
5285 assert_eq!(node_txn[0].input.len(), 1);
5286 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5287 check_spends!(node_txn[0], local_txn[0]);
5291 mine_transaction(&nodes[0], &htlc_timeout);
5292 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5293 expect_payment_failed!(nodes[0], our_payment_hash, false);
5295 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5296 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5297 assert_eq!(spend_txn.len(), 3);
5298 check_spends!(spend_txn[0], local_txn[0]);
5299 assert_eq!(spend_txn[1].input.len(), 1);
5300 check_spends!(spend_txn[1], htlc_timeout);
5301 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5302 assert_eq!(spend_txn[2].input.len(), 2);
5303 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5304 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5305 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5309 fn test_key_derivation_params() {
5310 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5311 // manager rotation to test that `channel_keys_id` returned in
5312 // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5313 // then derive a `delayed_payment_key`.
5315 let chanmon_cfgs = create_chanmon_cfgs(3);
5317 // We manually create the node configuration to backup the seed.
5318 let seed = [42; 32];
5319 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5320 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);
5321 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5322 let scorer = Mutex::new(test_utils::TestScorer::new());
5323 let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5324 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)) };
5325 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5326 node_cfgs.remove(0);
5327 node_cfgs.insert(0, node);
5329 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5330 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5332 // Create some initial channels
5333 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5335 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5336 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5337 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5339 // Ensure all nodes are at the same height
5340 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5341 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5342 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5343 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5345 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5346 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5347 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5348 assert_eq!(local_txn_1[0].input.len(), 1);
5349 check_spends!(local_txn_1[0], chan_1.3);
5351 // We check funding pubkey are unique
5352 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]));
5353 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]));
5354 if from_0_funding_key_0 == from_1_funding_key_0
5355 || from_0_funding_key_0 == from_1_funding_key_1
5356 || from_0_funding_key_1 == from_1_funding_key_0
5357 || from_0_funding_key_1 == from_1_funding_key_1 {
5358 panic!("Funding pubkeys aren't unique");
5361 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5362 mine_transaction(&nodes[0], &local_txn_1[0]);
5363 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5364 check_closed_broadcast!(nodes[0], true);
5365 check_added_monitors!(nodes[0], 1);
5366 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5368 let htlc_timeout = {
5369 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5370 assert_eq!(node_txn.len(), 1);
5371 assert_eq!(node_txn[0].input.len(), 1);
5372 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5373 check_spends!(node_txn[0], local_txn_1[0]);
5377 mine_transaction(&nodes[0], &htlc_timeout);
5378 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5379 expect_payment_failed!(nodes[0], our_payment_hash, false);
5381 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5382 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5383 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5384 assert_eq!(spend_txn.len(), 3);
5385 check_spends!(spend_txn[0], local_txn_1[0]);
5386 assert_eq!(spend_txn[1].input.len(), 1);
5387 check_spends!(spend_txn[1], htlc_timeout);
5388 assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5389 assert_eq!(spend_txn[2].input.len(), 2);
5390 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5391 assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5392 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5396 fn test_static_output_closing_tx() {
5397 let chanmon_cfgs = create_chanmon_cfgs(2);
5398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5400 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5402 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5404 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5405 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5407 mine_transaction(&nodes[0], &closing_tx);
5408 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5409 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5411 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5412 assert_eq!(spend_txn.len(), 1);
5413 check_spends!(spend_txn[0], closing_tx);
5415 mine_transaction(&nodes[1], &closing_tx);
5416 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5417 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5419 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5420 assert_eq!(spend_txn.len(), 1);
5421 check_spends!(spend_txn[0], closing_tx);
5424 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5425 let chanmon_cfgs = create_chanmon_cfgs(2);
5426 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5427 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5428 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5429 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5431 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5433 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5434 // present in B's local commitment transaction, but none of A's commitment transactions.
5435 nodes[1].node.claim_funds(payment_preimage);
5436 check_added_monitors!(nodes[1], 1);
5437 expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5439 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5440 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5441 expect_payment_sent_without_paths!(nodes[0], payment_preimage);
5443 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5444 check_added_monitors!(nodes[0], 1);
5445 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5446 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5447 check_added_monitors!(nodes[1], 1);
5449 let starting_block = nodes[1].best_block_info();
5450 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5451 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5452 connect_block(&nodes[1], &block);
5453 block.header.prev_blockhash = block.block_hash();
5455 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5456 check_closed_broadcast!(nodes[1], true);
5457 check_added_monitors!(nodes[1], 1);
5458 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5461 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5462 let chanmon_cfgs = create_chanmon_cfgs(2);
5463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5465 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5466 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5468 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5469 nodes[0].node.send_payment_with_route(&route, payment_hash,
5470 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5471 check_added_monitors!(nodes[0], 1);
5473 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5475 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5476 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5477 // to "time out" the HTLC.
5479 let starting_block = nodes[1].best_block_info();
5480 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5482 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5483 connect_block(&nodes[0], &block);
5484 block.header.prev_blockhash = block.block_hash();
5486 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5487 check_closed_broadcast!(nodes[0], true);
5488 check_added_monitors!(nodes[0], 1);
5489 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5492 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5493 let chanmon_cfgs = create_chanmon_cfgs(3);
5494 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5495 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5496 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5497 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5499 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5500 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5501 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5502 // actually revoked.
5503 let htlc_value = if use_dust { 50000 } else { 3000000 };
5504 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5505 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5506 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5507 check_added_monitors!(nodes[1], 1);
5509 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5510 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5511 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5512 check_added_monitors!(nodes[0], 1);
5513 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5514 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5515 check_added_monitors!(nodes[1], 1);
5516 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5517 check_added_monitors!(nodes[1], 1);
5518 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5520 if check_revoke_no_close {
5521 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5522 check_added_monitors!(nodes[0], 1);
5525 let starting_block = nodes[1].best_block_info();
5526 let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5527 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5528 connect_block(&nodes[0], &block);
5529 block.header.prev_blockhash = block.block_hash();
5531 if !check_revoke_no_close {
5532 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5533 check_closed_broadcast!(nodes[0], true);
5534 check_added_monitors!(nodes[0], 1);
5535 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5537 expect_payment_failed!(nodes[0], our_payment_hash, true);
5541 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5542 // There are only a few cases to test here:
5543 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5544 // broadcastable commitment transactions result in channel closure,
5545 // * its included in an unrevoked-but-previous remote commitment transaction,
5546 // * its included in the latest remote or local commitment transactions.
5547 // We test each of the three possible commitment transactions individually and use both dust and
5549 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5550 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5551 // tested for at least one of the cases in other tests.
5553 fn htlc_claim_single_commitment_only_a() {
5554 do_htlc_claim_local_commitment_only(true);
5555 do_htlc_claim_local_commitment_only(false);
5557 do_htlc_claim_current_remote_commitment_only(true);
5558 do_htlc_claim_current_remote_commitment_only(false);
5562 fn htlc_claim_single_commitment_only_b() {
5563 do_htlc_claim_previous_remote_commitment_only(true, false);
5564 do_htlc_claim_previous_remote_commitment_only(false, false);
5565 do_htlc_claim_previous_remote_commitment_only(true, true);
5566 do_htlc_claim_previous_remote_commitment_only(false, true);
5571 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5572 let chanmon_cfgs = create_chanmon_cfgs(2);
5573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5575 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5576 // Force duplicate randomness for every get-random call
5577 for node in nodes.iter() {
5578 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5581 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5582 let channel_value_satoshis=10000;
5583 let push_msat=10001;
5584 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5585 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5586 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5587 get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5589 // Create a second channel with the same random values. This used to panic due to a colliding
5590 // channel_id, but now panics due to a colliding outbound SCID alias.
5591 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5595 fn bolt2_open_channel_sending_node_checks_part2() {
5596 let chanmon_cfgs = create_chanmon_cfgs(2);
5597 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5598 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5599 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5601 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5602 let channel_value_satoshis=2^24;
5603 let push_msat=10001;
5604 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5606 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5607 let channel_value_satoshis=10000;
5608 // Test when push_msat is equal to 1000 * funding_satoshis.
5609 let push_msat=1000*channel_value_satoshis+1;
5610 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5612 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5613 let channel_value_satoshis=10000;
5614 let push_msat=10001;
5615 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
5616 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5617 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5619 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5620 // 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
5621 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5623 // 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.
5624 assert!(BREAKDOWN_TIMEOUT>0);
5625 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5627 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5628 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5629 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5631 // 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.
5632 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5633 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5634 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5635 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5636 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5640 fn bolt2_open_channel_sane_dust_limit() {
5641 let chanmon_cfgs = create_chanmon_cfgs(2);
5642 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5643 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5644 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5646 let channel_value_satoshis=1000000;
5647 let push_msat=10001;
5648 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5649 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5650 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5651 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5653 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5654 let events = nodes[1].node.get_and_clear_pending_msg_events();
5655 let err_msg = match events[0] {
5656 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5659 _ => panic!("Unexpected event"),
5661 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5664 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5665 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5666 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5667 // is no longer affordable once it's freed.
5669 fn test_fail_holding_cell_htlc_upon_free() {
5670 let chanmon_cfgs = create_chanmon_cfgs(2);
5671 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5672 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5673 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5674 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5676 // First nodes[0] generates an update_fee, setting the channel's
5677 // pending_update_fee.
5679 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5680 *feerate_lock += 20;
5682 nodes[0].node.timer_tick_occurred();
5683 check_added_monitors!(nodes[0], 1);
5685 let events = nodes[0].node.get_and_clear_pending_msg_events();
5686 assert_eq!(events.len(), 1);
5687 let (update_msg, commitment_signed) = match events[0] {
5688 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5689 (update_fee.as_ref(), commitment_signed)
5691 _ => panic!("Unexpected event"),
5694 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5696 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5697 let channel_reserve = chan_stat.channel_reserve_msat;
5698 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5699 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5701 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5702 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5703 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5705 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5706 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5707 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5708 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5709 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5711 // Flush the pending fee update.
5712 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5713 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5714 check_added_monitors!(nodes[1], 1);
5715 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5716 check_added_monitors!(nodes[0], 1);
5718 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5719 // HTLC, but now that the fee has been raised the payment will now fail, causing
5720 // us to surface its failure to the user.
5721 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5722 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5723 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);
5725 // Check that the payment failed to be sent out.
5726 let events = nodes[0].node.get_and_clear_pending_events();
5727 assert_eq!(events.len(), 2);
5729 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5730 assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5731 assert_eq!(our_payment_hash.clone(), *payment_hash);
5732 assert_eq!(*payment_failed_permanently, false);
5733 assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5735 _ => panic!("Unexpected event"),
5738 &Event::PaymentFailed { ref payment_hash, .. } => {
5739 assert_eq!(our_payment_hash.clone(), *payment_hash);
5741 _ => panic!("Unexpected event"),
5745 // Test that if multiple HTLCs are released from the holding cell and one is
5746 // valid but the other is no longer valid upon release, the valid HTLC can be
5747 // successfully completed while the other one fails as expected.
5749 fn test_free_and_fail_holding_cell_htlcs() {
5750 let chanmon_cfgs = create_chanmon_cfgs(2);
5751 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5752 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5753 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5754 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5756 // First nodes[0] generates an update_fee, setting the channel's
5757 // pending_update_fee.
5759 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5760 *feerate_lock += 200;
5762 nodes[0].node.timer_tick_occurred();
5763 check_added_monitors!(nodes[0], 1);
5765 let events = nodes[0].node.get_and_clear_pending_msg_events();
5766 assert_eq!(events.len(), 1);
5767 let (update_msg, commitment_signed) = match events[0] {
5768 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5769 (update_fee.as_ref(), commitment_signed)
5771 _ => panic!("Unexpected event"),
5774 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5776 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5777 let channel_reserve = chan_stat.channel_reserve_msat;
5778 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5779 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
5781 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5783 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, opt_anchors) - amt_1;
5784 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5785 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5787 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5788 nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
5789 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
5790 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5791 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5792 let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
5793 nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
5794 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
5795 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5796 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
5798 // Flush the pending fee update.
5799 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5800 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5801 check_added_monitors!(nodes[1], 1);
5802 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
5803 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5804 check_added_monitors!(nodes[0], 2);
5806 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
5807 // but now that the fee has been raised the second payment will now fail, causing us
5808 // to surface its failure to the user. The first payment should succeed.
5809 chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5810 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5811 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);
5813 // Check that the second payment failed to be sent out.
5814 let events = nodes[0].node.get_and_clear_pending_events();
5815 assert_eq!(events.len(), 2);
5817 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5818 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
5819 assert_eq!(payment_hash_2.clone(), *payment_hash);
5820 assert_eq!(*payment_failed_permanently, false);
5821 assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
5823 _ => panic!("Unexpected event"),
5826 &Event::PaymentFailed { ref payment_hash, .. } => {
5827 assert_eq!(payment_hash_2.clone(), *payment_hash);
5829 _ => panic!("Unexpected event"),
5832 // Complete the first payment and the RAA from the fee update.
5833 let (payment_event, send_raa_event) = {
5834 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
5835 assert_eq!(msgs.len(), 2);
5836 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
5838 let raa = match send_raa_event {
5839 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
5840 _ => panic!("Unexpected event"),
5842 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5843 check_added_monitors!(nodes[1], 1);
5844 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5845 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5846 let events = nodes[1].node.get_and_clear_pending_events();
5847 assert_eq!(events.len(), 1);
5849 Event::PendingHTLCsForwardable { .. } => {},
5850 _ => panic!("Unexpected event"),
5852 nodes[1].node.process_pending_htlc_forwards();
5853 let events = nodes[1].node.get_and_clear_pending_events();
5854 assert_eq!(events.len(), 1);
5856 Event::PaymentClaimable { .. } => {},
5857 _ => panic!("Unexpected event"),
5859 nodes[1].node.claim_funds(payment_preimage_1);
5860 check_added_monitors!(nodes[1], 1);
5861 expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
5863 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5864 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
5865 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
5866 expect_payment_sent!(nodes[0], payment_preimage_1);
5869 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
5870 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
5871 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
5874 fn test_fail_holding_cell_htlc_upon_free_multihop() {
5875 let chanmon_cfgs = create_chanmon_cfgs(3);
5876 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5877 // Avoid having to include routing fees in calculations
5878 let mut config = test_default_channel_config();
5879 config.channel_config.forwarding_fee_base_msat = 0;
5880 config.channel_config.forwarding_fee_proportional_millionths = 0;
5881 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5882 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5883 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5884 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
5886 // First nodes[1] generates an update_fee, setting the channel's
5887 // pending_update_fee.
5889 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
5890 *feerate_lock += 20;
5892 nodes[1].node.timer_tick_occurred();
5893 check_added_monitors!(nodes[1], 1);
5895 let events = nodes[1].node.get_and_clear_pending_msg_events();
5896 assert_eq!(events.len(), 1);
5897 let (update_msg, commitment_signed) = match events[0] {
5898 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5899 (update_fee.as_ref(), commitment_signed)
5901 _ => panic!("Unexpected event"),
5904 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
5906 let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
5907 let channel_reserve = chan_stat.channel_reserve_msat;
5908 let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
5909 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan_0_1.2);
5911 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5912 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
5913 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
5914 let payment_event = {
5915 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5916 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5917 check_added_monitors!(nodes[0], 1);
5919 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5920 assert_eq!(events.len(), 1);
5922 SendEvent::from_event(events.remove(0))
5924 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5925 check_added_monitors!(nodes[1], 0);
5926 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5927 expect_pending_htlcs_forwardable!(nodes[1]);
5929 chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
5930 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5932 // Flush the pending fee update.
5933 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
5934 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5935 check_added_monitors!(nodes[2], 1);
5936 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
5937 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
5938 check_added_monitors!(nodes[1], 2);
5940 // A final RAA message is generated to finalize the fee update.
5941 let events = nodes[1].node.get_and_clear_pending_msg_events();
5942 assert_eq!(events.len(), 1);
5944 let raa_msg = match &events[0] {
5945 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
5948 _ => panic!("Unexpected event"),
5951 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
5952 check_added_monitors!(nodes[2], 1);
5953 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
5955 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
5956 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
5957 assert_eq!(process_htlc_forwards_event.len(), 2);
5958 match &process_htlc_forwards_event[0] {
5959 &Event::PendingHTLCsForwardable { .. } => {},
5960 _ => panic!("Unexpected event"),
5963 // In response, we call ChannelManager's process_pending_htlc_forwards
5964 nodes[1].node.process_pending_htlc_forwards();
5965 check_added_monitors!(nodes[1], 1);
5967 // This causes the HTLC to be failed backwards.
5968 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
5969 assert_eq!(fail_event.len(), 1);
5970 let (fail_msg, commitment_signed) = match &fail_event[0] {
5971 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
5972 assert_eq!(updates.update_add_htlcs.len(), 0);
5973 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
5974 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
5975 assert_eq!(updates.update_fail_htlcs.len(), 1);
5976 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
5978 _ => panic!("Unexpected event"),
5981 // Pass the failure messages back to nodes[0].
5982 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5983 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
5985 // Complete the HTLC failure+removal process.
5986 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5987 check_added_monitors!(nodes[0], 1);
5988 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
5989 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
5990 check_added_monitors!(nodes[1], 2);
5991 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
5992 assert_eq!(final_raa_event.len(), 1);
5993 let raa = match &final_raa_event[0] {
5994 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
5995 _ => panic!("Unexpected event"),
5997 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
5998 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
5999 check_added_monitors!(nodes[0], 1);
6002 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6003 // 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.
6004 //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.
6007 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6008 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6009 let chanmon_cfgs = create_chanmon_cfgs(2);
6010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6012 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6013 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6015 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6016 route.paths[0].hops[0].fee_msat = 100;
6018 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6019 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6020 ), true, APIError::ChannelUnavailable { .. }, {});
6021 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6025 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6026 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6027 let chanmon_cfgs = create_chanmon_cfgs(2);
6028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6030 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6031 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6033 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6034 route.paths[0].hops[0].fee_msat = 0;
6035 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6036 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6037 true, APIError::ChannelUnavailable { ref err },
6038 assert_eq!(err, "Cannot send 0-msat HTLC"));
6040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6041 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6045 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6046 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6047 let chanmon_cfgs = create_chanmon_cfgs(2);
6048 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6049 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6050 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6051 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6053 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6054 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6055 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6056 check_added_monitors!(nodes[0], 1);
6057 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6058 updates.update_add_htlcs[0].amount_msat = 0;
6060 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6061 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6062 check_closed_broadcast!(nodes[1], true).unwrap();
6063 check_added_monitors!(nodes[1], 1);
6064 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6068 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6069 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6070 //It is enforced when constructing a route.
6071 let chanmon_cfgs = create_chanmon_cfgs(2);
6072 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6073 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6074 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6075 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6077 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6078 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
6079 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6080 route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6081 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6082 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6083 ), true, APIError::InvalidRoute { ref err },
6084 assert_eq!(err, &"Channel CLTV overflowed?"));
6088 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6089 //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.
6090 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6091 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6092 let chanmon_cfgs = create_chanmon_cfgs(2);
6093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6095 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6096 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6097 let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6098 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6100 // Fetch a route in advance as we will be unable to once we're unable to send.
6101 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6102 for i in 0..max_accepted_htlcs {
6103 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6104 let payment_event = {
6105 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6106 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6107 check_added_monitors!(nodes[0], 1);
6109 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6110 assert_eq!(events.len(), 1);
6111 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6112 assert_eq!(htlcs[0].htlc_id, i);
6116 SendEvent::from_event(events.remove(0))
6118 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6119 check_added_monitors!(nodes[1], 0);
6120 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6122 expect_pending_htlcs_forwardable!(nodes[1]);
6123 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6125 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6126 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6127 ), true, APIError::ChannelUnavailable { .. }, {});
6129 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6133 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6134 //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.
6135 let chanmon_cfgs = create_chanmon_cfgs(2);
6136 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6137 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6138 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6139 let channel_value = 100000;
6140 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6141 let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6143 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6145 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6146 // Manually create a route over our max in flight (which our router normally automatically
6148 route.paths[0].hops[0].fee_msat = max_in_flight + 1;
6149 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6150 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6151 ), true, APIError::ChannelUnavailable { .. }, {});
6152 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6154 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6157 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6159 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6160 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6161 let chanmon_cfgs = create_chanmon_cfgs(2);
6162 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6163 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6164 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6165 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6166 let htlc_minimum_msat: u64;
6168 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6169 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6170 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6171 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6174 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6175 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6176 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6177 check_added_monitors!(nodes[0], 1);
6178 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6179 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6180 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6181 assert!(nodes[1].node.list_channels().is_empty());
6182 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6183 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()));
6184 check_added_monitors!(nodes[1], 1);
6185 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6189 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6190 //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
6191 let chanmon_cfgs = create_chanmon_cfgs(2);
6192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6194 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6195 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6197 let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6198 let channel_reserve = chan_stat.channel_reserve_msat;
6199 let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6200 let opt_anchors = get_opt_anchors!(nodes[0], nodes[1], chan.2);
6201 // The 2* and +1 are for the fee spike reserve.
6202 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, opt_anchors);
6204 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6205 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6206 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6207 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6208 check_added_monitors!(nodes[0], 1);
6209 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6211 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6212 // at this time channel-initiatee receivers are not required to enforce that senders
6213 // respect the fee_spike_reserve.
6214 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6215 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6217 assert!(nodes[1].node.list_channels().is_empty());
6218 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6219 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6220 check_added_monitors!(nodes[1], 1);
6221 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6225 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6226 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6227 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6228 let chanmon_cfgs = create_chanmon_cfgs(2);
6229 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6230 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6231 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6232 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6234 let send_amt = 3999999;
6235 let (mut route, our_payment_hash, _, our_payment_secret) =
6236 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6237 route.paths[0].hops[0].fee_msat = send_amt;
6238 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6239 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6240 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6241 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6242 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6243 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6245 let mut msg = msgs::UpdateAddHTLC {
6249 payment_hash: our_payment_hash,
6250 cltv_expiry: htlc_cltv,
6251 onion_routing_packet: onion_packet.clone(),
6255 msg.htlc_id = i as u64;
6256 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6258 msg.htlc_id = (50) as u64;
6259 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6261 assert!(nodes[1].node.list_channels().is_empty());
6262 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6263 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6264 check_added_monitors!(nodes[1], 1);
6265 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6269 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6270 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6271 let chanmon_cfgs = create_chanmon_cfgs(2);
6272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6274 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6275 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6277 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6278 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6279 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6280 check_added_monitors!(nodes[0], 1);
6281 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6282 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;
6283 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6285 assert!(nodes[1].node.list_channels().is_empty());
6286 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6287 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6288 check_added_monitors!(nodes[1], 1);
6289 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6293 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6294 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6295 let chanmon_cfgs = create_chanmon_cfgs(2);
6296 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6297 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6298 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6300 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6301 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6302 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6303 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6304 check_added_monitors!(nodes[0], 1);
6305 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6306 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6307 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6309 assert!(nodes[1].node.list_channels().is_empty());
6310 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6311 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6312 check_added_monitors!(nodes[1], 1);
6313 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6317 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6318 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6319 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6320 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6321 let chanmon_cfgs = create_chanmon_cfgs(2);
6322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6326 create_announced_chan_between_nodes(&nodes, 0, 1);
6327 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6328 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6329 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6330 check_added_monitors!(nodes[0], 1);
6331 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6332 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6334 //Disconnect and Reconnect
6335 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6336 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6337 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();
6338 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6339 assert_eq!(reestablish_1.len(), 1);
6340 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();
6341 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6342 assert_eq!(reestablish_2.len(), 1);
6343 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6344 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6345 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6346 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6349 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6350 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6351 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6352 check_added_monitors!(nodes[1], 1);
6353 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6355 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6357 assert!(nodes[1].node.list_channels().is_empty());
6358 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6359 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6360 check_added_monitors!(nodes[1], 1);
6361 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6365 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6366 //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.
6368 let chanmon_cfgs = create_chanmon_cfgs(2);
6369 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6370 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6371 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6372 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6373 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6374 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6375 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6377 check_added_monitors!(nodes[0], 1);
6378 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6379 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6381 let update_msg = msgs::UpdateFulfillHTLC{
6384 payment_preimage: our_payment_preimage,
6387 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6389 assert!(nodes[0].node.list_channels().is_empty());
6390 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6391 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()));
6392 check_added_monitors!(nodes[0], 1);
6393 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6397 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6398 //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.
6400 let chanmon_cfgs = create_chanmon_cfgs(2);
6401 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6402 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6403 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6404 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6406 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6407 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6408 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6409 check_added_monitors!(nodes[0], 1);
6410 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6411 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6413 let update_msg = msgs::UpdateFailHTLC{
6416 reason: msgs::OnionErrorPacket { data: Vec::new()},
6419 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6421 assert!(nodes[0].node.list_channels().is_empty());
6422 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6423 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()));
6424 check_added_monitors!(nodes[0], 1);
6425 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6429 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6430 //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.
6432 let chanmon_cfgs = create_chanmon_cfgs(2);
6433 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6434 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6435 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6436 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6438 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6439 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6440 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6441 check_added_monitors!(nodes[0], 1);
6442 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6443 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6444 let update_msg = msgs::UpdateFailMalformedHTLC{
6447 sha256_of_onion: [1; 32],
6448 failure_code: 0x8000,
6451 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6453 assert!(nodes[0].node.list_channels().is_empty());
6454 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6455 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()));
6456 check_added_monitors!(nodes[0], 1);
6457 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6461 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6462 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6464 let chanmon_cfgs = create_chanmon_cfgs(2);
6465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6467 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6468 create_announced_chan_between_nodes(&nodes, 0, 1);
6470 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6472 nodes[1].node.claim_funds(our_payment_preimage);
6473 check_added_monitors!(nodes[1], 1);
6474 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6476 let events = nodes[1].node.get_and_clear_pending_msg_events();
6477 assert_eq!(events.len(), 1);
6478 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6480 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, .. } } => {
6481 assert!(update_add_htlcs.is_empty());
6482 assert_eq!(update_fulfill_htlcs.len(), 1);
6483 assert!(update_fail_htlcs.is_empty());
6484 assert!(update_fail_malformed_htlcs.is_empty());
6485 assert!(update_fee.is_none());
6486 update_fulfill_htlcs[0].clone()
6488 _ => panic!("Unexpected event"),
6492 update_fulfill_msg.htlc_id = 1;
6494 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6496 assert!(nodes[0].node.list_channels().is_empty());
6497 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6498 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6499 check_added_monitors!(nodes[0], 1);
6500 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6504 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6505 //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.
6507 let chanmon_cfgs = create_chanmon_cfgs(2);
6508 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6509 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6510 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6511 create_announced_chan_between_nodes(&nodes, 0, 1);
6513 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6515 nodes[1].node.claim_funds(our_payment_preimage);
6516 check_added_monitors!(nodes[1], 1);
6517 expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6519 let events = nodes[1].node.get_and_clear_pending_msg_events();
6520 assert_eq!(events.len(), 1);
6521 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6523 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6524 assert!(update_add_htlcs.is_empty());
6525 assert_eq!(update_fulfill_htlcs.len(), 1);
6526 assert!(update_fail_htlcs.is_empty());
6527 assert!(update_fail_malformed_htlcs.is_empty());
6528 assert!(update_fee.is_none());
6529 update_fulfill_htlcs[0].clone()
6531 _ => panic!("Unexpected event"),
6535 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6537 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6539 assert!(nodes[0].node.list_channels().is_empty());
6540 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6541 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6542 check_added_monitors!(nodes[0], 1);
6543 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6547 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6548 //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.
6550 let chanmon_cfgs = create_chanmon_cfgs(2);
6551 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6552 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6553 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6554 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6556 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6557 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6558 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6559 check_added_monitors!(nodes[0], 1);
6561 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6562 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6564 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6565 check_added_monitors!(nodes[1], 0);
6566 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6568 let events = nodes[1].node.get_and_clear_pending_msg_events();
6570 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6572 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, .. } } => {
6573 assert!(update_add_htlcs.is_empty());
6574 assert!(update_fulfill_htlcs.is_empty());
6575 assert!(update_fail_htlcs.is_empty());
6576 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6577 assert!(update_fee.is_none());
6578 update_fail_malformed_htlcs[0].clone()
6580 _ => panic!("Unexpected event"),
6583 update_msg.failure_code &= !0x8000;
6584 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6586 assert!(nodes[0].node.list_channels().is_empty());
6587 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6588 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6589 check_added_monitors!(nodes[0], 1);
6590 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6594 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6595 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6596 // * 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.
6598 let chanmon_cfgs = create_chanmon_cfgs(3);
6599 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6600 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6601 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6602 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6603 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6605 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6608 let mut payment_event = {
6609 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6610 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6611 check_added_monitors!(nodes[0], 1);
6612 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6613 assert_eq!(events.len(), 1);
6614 SendEvent::from_event(events.remove(0))
6616 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6617 check_added_monitors!(nodes[1], 0);
6618 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6619 expect_pending_htlcs_forwardable!(nodes[1]);
6620 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6621 assert_eq!(events_2.len(), 1);
6622 check_added_monitors!(nodes[1], 1);
6623 payment_event = SendEvent::from_event(events_2.remove(0));
6624 assert_eq!(payment_event.msgs.len(), 1);
6627 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6628 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6629 check_added_monitors!(nodes[2], 0);
6630 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6632 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6633 assert_eq!(events_3.len(), 1);
6634 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6636 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 } } => {
6637 assert!(update_add_htlcs.is_empty());
6638 assert!(update_fulfill_htlcs.is_empty());
6639 assert!(update_fail_htlcs.is_empty());
6640 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6641 assert!(update_fee.is_none());
6642 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6644 _ => panic!("Unexpected event"),
6648 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6650 check_added_monitors!(nodes[1], 0);
6651 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6652 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 }]);
6653 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6654 assert_eq!(events_4.len(), 1);
6656 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
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, .. } } => {
6659 assert!(update_add_htlcs.is_empty());
6660 assert!(update_fulfill_htlcs.is_empty());
6661 assert_eq!(update_fail_htlcs.len(), 1);
6662 assert!(update_fail_malformed_htlcs.is_empty());
6663 assert!(update_fee.is_none());
6665 _ => panic!("Unexpected event"),
6668 check_added_monitors!(nodes[1], 1);
6672 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6673 let chanmon_cfgs = create_chanmon_cfgs(3);
6674 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6675 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6676 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6677 create_announced_chan_between_nodes(&nodes, 0, 1);
6678 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6680 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6683 let mut payment_event = {
6684 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6685 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6686 check_added_monitors!(nodes[0], 1);
6687 SendEvent::from_node(&nodes[0])
6690 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6691 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6692 expect_pending_htlcs_forwardable!(nodes[1]);
6693 check_added_monitors!(nodes[1], 1);
6694 payment_event = SendEvent::from_node(&nodes[1]);
6695 assert_eq!(payment_event.msgs.len(), 1);
6698 payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6699 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6700 check_added_monitors!(nodes[2], 0);
6701 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6703 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6704 assert_eq!(events_3.len(), 1);
6706 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6707 let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6708 // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6709 update_msg.failure_code |= 0x2000;
6711 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6712 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6714 _ => panic!("Unexpected event"),
6717 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6718 vec![HTLCDestination::NextHopChannel {
6719 node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6720 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6721 assert_eq!(events_4.len(), 1);
6722 check_added_monitors!(nodes[1], 1);
6725 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6726 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6727 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6729 _ => panic!("Unexpected event"),
6732 let events_5 = nodes[0].node.get_and_clear_pending_events();
6733 assert_eq!(events_5.len(), 2);
6735 // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6736 // the node originating the error to its next hop.
6738 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6740 assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6741 assert!(is_permanent);
6742 assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6744 _ => panic!("Unexpected event"),
6747 Event::PaymentFailed { payment_hash, .. } => {
6748 assert_eq!(payment_hash, our_payment_hash);
6750 _ => panic!("Unexpected event"),
6753 // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6756 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6757 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6758 // 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
6759 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6761 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6762 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6765 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6766 let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
6768 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6769 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6771 // We route 2 dust-HTLCs between A and B
6772 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6773 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6774 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6776 // Cache one local commitment tx as previous
6777 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6779 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6780 nodes[1].node.fail_htlc_backwards(&payment_hash_2);
6781 check_added_monitors!(nodes[1], 0);
6782 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
6783 check_added_monitors!(nodes[1], 1);
6785 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6786 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6787 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6788 check_added_monitors!(nodes[0], 1);
6790 // Cache one local commitment tx as lastest
6791 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6793 let events = nodes[0].node.get_and_clear_pending_msg_events();
6795 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6796 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6798 _ => panic!("Unexpected event"),
6801 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6802 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6804 _ => panic!("Unexpected event"),
6807 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6808 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6809 if announce_latest {
6810 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6812 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6815 check_closed_broadcast!(nodes[0], true);
6816 check_added_monitors!(nodes[0], 1);
6817 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6819 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6820 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6821 let events = nodes[0].node.get_and_clear_pending_events();
6822 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6823 assert_eq!(events.len(), 4);
6824 let mut first_failed = false;
6825 for event in events {
6827 Event::PaymentPathFailed { payment_hash, .. } => {
6828 if payment_hash == payment_hash_1 {
6829 assert!(!first_failed);
6830 first_failed = true;
6832 assert_eq!(payment_hash, payment_hash_2);
6835 Event::PaymentFailed { .. } => {}
6836 _ => panic!("Unexpected event"),
6842 fn test_failure_delay_dust_htlc_local_commitment() {
6843 do_test_failure_delay_dust_htlc_local_commitment(true);
6844 do_test_failure_delay_dust_htlc_local_commitment(false);
6847 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6848 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6849 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6850 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6851 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6852 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6853 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6855 let chanmon_cfgs = create_chanmon_cfgs(3);
6856 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6857 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6858 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6859 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6861 let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6862 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6864 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6865 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6867 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6868 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6870 // We revoked bs_commitment_tx
6872 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6873 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6876 let mut timeout_tx = Vec::new();
6878 // We fail dust-HTLC 1 by broadcast of local commitment tx
6879 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6880 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6881 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6882 expect_payment_failed!(nodes[0], dust_hash, false);
6884 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6885 check_closed_broadcast!(nodes[0], true);
6886 check_added_monitors!(nodes[0], 1);
6887 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6888 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6889 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6890 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6891 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6892 mine_transaction(&nodes[0], &timeout_tx[0]);
6893 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6894 expect_payment_failed!(nodes[0], non_dust_hash, false);
6896 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6897 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6898 check_closed_broadcast!(nodes[0], true);
6899 check_added_monitors!(nodes[0], 1);
6900 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6901 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6903 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
6904 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
6905 .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
6906 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
6907 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
6908 // dust HTLC should have been failed.
6909 expect_payment_failed!(nodes[0], dust_hash, false);
6912 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6914 assert_eq!(timeout_tx[0].lock_time.0, 11);
6916 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
6917 mine_transaction(&nodes[0], &timeout_tx[0]);
6918 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6919 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6920 expect_payment_failed!(nodes[0], non_dust_hash, false);
6925 fn test_sweep_outbound_htlc_failure_update() {
6926 do_test_sweep_outbound_htlc_failure_update(false, true);
6927 do_test_sweep_outbound_htlc_failure_update(false, false);
6928 do_test_sweep_outbound_htlc_failure_update(true, false);
6932 fn test_user_configurable_csv_delay() {
6933 // We test our channel constructors yield errors when we pass them absurd csv delay
6935 let mut low_our_to_self_config = UserConfig::default();
6936 low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
6937 let mut high_their_to_self_config = UserConfig::default();
6938 high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
6939 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6940 let chanmon_cfgs = create_chanmon_cfgs(2);
6941 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6942 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6943 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6945 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6946 if let Err(error) = Channel::new_outbound(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6947 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
6948 &low_our_to_self_config, 0, 42)
6951 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())); },
6952 _ => panic!("Unexpected event"),
6954 } else { assert!(false) }
6956 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6957 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6958 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6959 open_channel.to_self_delay = 200;
6960 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6961 &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,
6962 &low_our_to_self_config, 0, &nodes[0].logger, 42)
6965 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())); },
6966 _ => panic!("Unexpected event"),
6968 } else { assert!(false); }
6970 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6971 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6972 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()));
6973 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6974 accept_channel.to_self_delay = 200;
6975 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
6977 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6979 &ErrorAction::SendErrorMessage { ref msg } => {
6980 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()));
6981 reason_msg = msg.data.clone();
6985 } else { panic!(); }
6986 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
6988 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6989 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6990 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6991 open_channel.to_self_delay = 200;
6992 if let Err(error) = Channel::new_from_req(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
6993 &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,
6994 &high_their_to_self_config, 0, &nodes[0].logger, 42)
6997 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())); },
6998 _ => panic!("Unexpected event"),
7000 } else { assert!(false); }
7004 fn test_check_htlc_underpaying() {
7005 // Send payment through A -> B but A is maliciously
7006 // sending a probe payment (i.e less than expected value0
7007 // to B, B should refuse payment.
7009 let chanmon_cfgs = create_chanmon_cfgs(2);
7010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7012 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7014 // Create some initial channels
7015 create_announced_chan_between_nodes(&nodes, 0, 1);
7017 let scorer = test_utils::TestScorer::new();
7018 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7019 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();
7020 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();
7021 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7022 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7023 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7024 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7025 check_added_monitors!(nodes[0], 1);
7027 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7028 assert_eq!(events.len(), 1);
7029 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7030 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7031 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7033 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7034 // and then will wait a second random delay before failing the HTLC back:
7035 expect_pending_htlcs_forwardable!(nodes[1]);
7036 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7038 // Node 3 is expecting payment of 100_000 but received 10_000,
7039 // it should fail htlc like we didn't know the preimage.
7040 nodes[1].node.process_pending_htlc_forwards();
7042 let events = nodes[1].node.get_and_clear_pending_msg_events();
7043 assert_eq!(events.len(), 1);
7044 let (update_fail_htlc, commitment_signed) = match events[0] {
7045 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 } } => {
7046 assert!(update_add_htlcs.is_empty());
7047 assert!(update_fulfill_htlcs.is_empty());
7048 assert_eq!(update_fail_htlcs.len(), 1);
7049 assert!(update_fail_malformed_htlcs.is_empty());
7050 assert!(update_fee.is_none());
7051 (update_fail_htlcs[0].clone(), commitment_signed)
7053 _ => panic!("Unexpected event"),
7055 check_added_monitors!(nodes[1], 1);
7057 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7058 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7060 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7061 let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7062 expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7063 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7067 fn test_announce_disable_channels() {
7068 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7069 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7071 let chanmon_cfgs = create_chanmon_cfgs(2);
7072 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7073 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7074 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7076 create_announced_chan_between_nodes(&nodes, 0, 1);
7077 create_announced_chan_between_nodes(&nodes, 1, 0);
7078 create_announced_chan_between_nodes(&nodes, 0, 1);
7081 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7082 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7084 for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7085 nodes[0].node.timer_tick_occurred();
7087 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7088 assert_eq!(msg_events.len(), 3);
7089 let mut chans_disabled = HashMap::new();
7090 for e in msg_events {
7092 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7093 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7094 // Check that each channel gets updated exactly once
7095 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7096 panic!("Generated ChannelUpdate for wrong chan!");
7099 _ => panic!("Unexpected event"),
7103 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();
7104 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7105 assert_eq!(reestablish_1.len(), 3);
7106 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();
7107 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7108 assert_eq!(reestablish_2.len(), 3);
7110 // Reestablish chan_1
7111 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7112 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7113 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7114 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7115 // Reestablish chan_2
7116 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7117 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7118 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7119 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7120 // Reestablish chan_3
7121 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7122 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7123 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7124 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7126 for _ in 0..ENABLE_GOSSIP_TICKS {
7127 nodes[0].node.timer_tick_occurred();
7129 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7130 nodes[0].node.timer_tick_occurred();
7131 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7132 assert_eq!(msg_events.len(), 3);
7133 for e in msg_events {
7135 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7136 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7137 match chans_disabled.remove(&msg.contents.short_channel_id) {
7138 // Each update should have a higher timestamp than the previous one, replacing
7140 Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7141 None => panic!("Generated ChannelUpdate for wrong chan!"),
7144 _ => panic!("Unexpected event"),
7147 // Check that each channel gets updated exactly once
7148 assert!(chans_disabled.is_empty());
7152 fn test_bump_penalty_txn_on_revoked_commitment() {
7153 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7154 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7156 let chanmon_cfgs = create_chanmon_cfgs(2);
7157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7159 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7161 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7163 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7164 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7165 .with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7166 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7167 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7169 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7170 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7171 assert_eq!(revoked_txn[0].output.len(), 4);
7172 assert_eq!(revoked_txn[0].input.len(), 1);
7173 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7174 let revoked_txid = revoked_txn[0].txid();
7176 let mut penalty_sum = 0;
7177 for outp in revoked_txn[0].output.iter() {
7178 if outp.script_pubkey.is_v0_p2wsh() {
7179 penalty_sum += outp.value;
7183 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7184 let header_114 = connect_blocks(&nodes[1], 14);
7186 // Actually revoke tx by claiming a HTLC
7187 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7188 connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7189 check_added_monitors!(nodes[1], 1);
7191 // One or more justice tx should have been broadcast, check it
7195 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7196 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7197 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7198 assert_eq!(node_txn[0].output.len(), 1);
7199 check_spends!(node_txn[0], revoked_txn[0]);
7200 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7201 feerate_1 = fee_1 * 1000 / node_txn[0].weight() as u64;
7202 penalty_1 = node_txn[0].txid();
7206 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7207 connect_blocks(&nodes[1], 15);
7208 let mut penalty_2 = penalty_1;
7209 let mut feerate_2 = 0;
7211 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7212 assert_eq!(node_txn.len(), 1);
7213 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7214 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7215 assert_eq!(node_txn[0].output.len(), 1);
7216 check_spends!(node_txn[0], revoked_txn[0]);
7217 penalty_2 = node_txn[0].txid();
7218 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7219 assert_ne!(penalty_2, penalty_1);
7220 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7221 feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7222 // Verify 25% bump heuristic
7223 assert!(feerate_2 * 100 >= feerate_1 * 125);
7227 assert_ne!(feerate_2, 0);
7229 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7230 connect_blocks(&nodes[1], 1);
7232 let mut feerate_3 = 0;
7234 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7235 assert_eq!(node_txn.len(), 1);
7236 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7237 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7238 assert_eq!(node_txn[0].output.len(), 1);
7239 check_spends!(node_txn[0], revoked_txn[0]);
7240 penalty_3 = node_txn[0].txid();
7241 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7242 assert_ne!(penalty_3, penalty_2);
7243 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7244 feerate_3 = fee_3 * 1000 / node_txn[0].weight() as u64;
7245 // Verify 25% bump heuristic
7246 assert!(feerate_3 * 100 >= feerate_2 * 125);
7250 assert_ne!(feerate_3, 0);
7252 nodes[1].node.get_and_clear_pending_events();
7253 nodes[1].node.get_and_clear_pending_msg_events();
7257 fn test_bump_penalty_txn_on_revoked_htlcs() {
7258 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7259 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7261 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7262 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7263 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7264 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7265 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7267 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7268 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7269 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
7270 let scorer = test_utils::TestScorer::new();
7271 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7272 let route = get_route(&nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(), None,
7273 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7274 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7275 let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50).with_bolt11_features(nodes[0].node.invoice_features()).unwrap();
7276 let route = get_route(&nodes[1].node.get_our_node_id(), &payment_params, &nodes[1].network_graph.read_only(), None,
7277 3_000_000, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
7278 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7280 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7281 assert_eq!(revoked_local_txn[0].input.len(), 1);
7282 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7284 // Revoke local commitment tx
7285 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7287 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7288 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7289 check_closed_broadcast!(nodes[1], true);
7290 check_added_monitors!(nodes[1], 1);
7291 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7292 connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7294 let revoked_htlc_txn = {
7295 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7296 assert_eq!(txn.len(), 2);
7298 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7299 assert_eq!(txn[0].input.len(), 1);
7300 check_spends!(txn[0], revoked_local_txn[0]);
7302 assert_eq!(txn[1].input.len(), 1);
7303 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7304 assert_eq!(txn[1].output.len(), 1);
7305 check_spends!(txn[1], revoked_local_txn[0]);
7310 // Broadcast set of revoked txn on A
7311 let hash_128 = connect_blocks(&nodes[0], 40);
7312 let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7313 connect_block(&nodes[0], &block_11);
7314 let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7315 connect_block(&nodes[0], &block_129);
7316 let events = nodes[0].node.get_and_clear_pending_events();
7317 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7318 match events.last().unwrap() {
7319 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7320 _ => panic!("Unexpected event"),
7326 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7327 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7328 // Verify claim tx are spending revoked HTLC txn
7330 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7331 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7332 // which are included in the same block (they are broadcasted because we scan the
7333 // transactions linearly and generate claims as we go, they likely should be removed in the
7335 assert_eq!(node_txn[0].input.len(), 1);
7336 check_spends!(node_txn[0], revoked_local_txn[0]);
7337 assert_eq!(node_txn[1].input.len(), 1);
7338 check_spends!(node_txn[1], revoked_local_txn[0]);
7339 assert_eq!(node_txn[2].input.len(), 1);
7340 check_spends!(node_txn[2], revoked_local_txn[0]);
7342 // Each of the three justice transactions claim a separate (single) output of the three
7343 // available, which we check here:
7344 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7345 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7346 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7348 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7349 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7351 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7352 // output, checked above).
7353 assert_eq!(node_txn[3].input.len(), 2);
7354 assert_eq!(node_txn[3].output.len(), 1);
7355 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7357 first = node_txn[3].txid();
7358 // Store both feerates for later comparison
7359 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7360 feerate_1 = fee_1 * 1000 / node_txn[3].weight() as u64;
7361 penalty_txn = vec![node_txn[2].clone()];
7365 // Connect one more block to see if bumped penalty are issued for HTLC txn
7366 let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7367 connect_block(&nodes[0], &block_130);
7368 let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7369 connect_block(&nodes[0], &block_131);
7371 // Few more blocks to confirm penalty txn
7372 connect_blocks(&nodes[0], 4);
7373 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7374 let header_144 = connect_blocks(&nodes[0], 9);
7376 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7377 assert_eq!(node_txn.len(), 1);
7379 assert_eq!(node_txn[0].input.len(), 2);
7380 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7381 // Verify bumped tx is different and 25% bump heuristic
7382 assert_ne!(first, node_txn[0].txid());
7383 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7384 let feerate_2 = fee_2 * 1000 / node_txn[0].weight() as u64;
7385 assert!(feerate_2 * 100 > feerate_1 * 125);
7386 let txn = vec![node_txn[0].clone()];
7390 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7391 connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7392 connect_blocks(&nodes[0], 20);
7394 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7395 // We verify than no new transaction has been broadcast because previously
7396 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7397 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7398 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7399 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7400 // up bumped justice generation.
7401 assert_eq!(node_txn.len(), 0);
7404 check_closed_broadcast!(nodes[0], true);
7405 check_added_monitors!(nodes[0], 1);
7409 fn test_bump_penalty_txn_on_remote_commitment() {
7410 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7411 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7414 // Provide preimage for one
7415 // Check aggregation
7417 let chanmon_cfgs = create_chanmon_cfgs(2);
7418 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7419 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7420 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7422 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7423 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7424 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7426 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7427 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7428 assert_eq!(remote_txn[0].output.len(), 4);
7429 assert_eq!(remote_txn[0].input.len(), 1);
7430 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7432 // Claim a HTLC without revocation (provide B monitor with preimage)
7433 nodes[1].node.claim_funds(payment_preimage);
7434 expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7435 mine_transaction(&nodes[1], &remote_txn[0]);
7436 check_added_monitors!(nodes[1], 2);
7437 connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7439 // One or more claim tx should have been broadcast, check it
7443 let feerate_timeout;
7444 let feerate_preimage;
7446 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7447 // 3 transactions including:
7448 // preimage and timeout sweeps from remote commitment + preimage sweep bump
7449 assert_eq!(node_txn.len(), 3);
7450 assert_eq!(node_txn[0].input.len(), 1);
7451 assert_eq!(node_txn[1].input.len(), 1);
7452 assert_eq!(node_txn[2].input.len(), 1);
7453 check_spends!(node_txn[0], remote_txn[0]);
7454 check_spends!(node_txn[1], remote_txn[0]);
7455 check_spends!(node_txn[2], remote_txn[0]);
7457 preimage = node_txn[0].txid();
7458 let index = node_txn[0].input[0].previous_output.vout;
7459 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7460 feerate_preimage = fee * 1000 / node_txn[0].weight() as u64;
7462 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7463 (node_txn[2].clone(), node_txn[1].clone())
7465 (node_txn[1].clone(), node_txn[2].clone())
7468 preimage_bump = preimage_bump_tx;
7469 check_spends!(preimage_bump, remote_txn[0]);
7470 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7472 timeout = timeout_tx.txid();
7473 let index = timeout_tx.input[0].previous_output.vout;
7474 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7475 feerate_timeout = fee * 1000 / timeout_tx.weight() as u64;
7479 assert_ne!(feerate_timeout, 0);
7480 assert_ne!(feerate_preimage, 0);
7482 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7483 connect_blocks(&nodes[1], 1);
7485 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7486 assert_eq!(node_txn.len(), 1);
7487 assert_eq!(node_txn[0].input.len(), 1);
7488 assert_eq!(preimage_bump.input.len(), 1);
7489 check_spends!(node_txn[0], remote_txn[0]);
7490 check_spends!(preimage_bump, remote_txn[0]);
7492 let index = preimage_bump.input[0].previous_output.vout;
7493 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7494 let new_feerate = fee * 1000 / preimage_bump.weight() as u64;
7495 assert!(new_feerate * 100 > feerate_timeout * 125);
7496 assert_ne!(timeout, preimage_bump.txid());
7498 let index = node_txn[0].input[0].previous_output.vout;
7499 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7500 let new_feerate = fee * 1000 / node_txn[0].weight() as u64;
7501 assert!(new_feerate * 100 > feerate_preimage * 125);
7502 assert_ne!(preimage, node_txn[0].txid());
7507 nodes[1].node.get_and_clear_pending_events();
7508 nodes[1].node.get_and_clear_pending_msg_events();
7512 fn test_counterparty_raa_skip_no_crash() {
7513 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7514 // commitment transaction, we would have happily carried on and provided them the next
7515 // commitment transaction based on one RAA forward. This would probably eventually have led to
7516 // channel closure, but it would not have resulted in funds loss. Still, our
7517 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7518 // check simply that the channel is closed in response to such an RAA, but don't check whether
7519 // we decide to punish our counterparty for revoking their funds (as we don't currently
7521 let chanmon_cfgs = create_chanmon_cfgs(2);
7522 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7523 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7524 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7525 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7527 let per_commitment_secret;
7528 let next_per_commitment_point;
7530 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7531 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7532 let keys = guard.channel_by_id.get_mut(&channel_id).unwrap().get_signer();
7534 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7536 // Make signer believe we got a counterparty signature, so that it allows the revocation
7537 keys.get_enforcement_state().last_holder_commitment -= 1;
7538 per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7540 // Must revoke without gaps
7541 keys.get_enforcement_state().last_holder_commitment -= 1;
7542 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7544 keys.get_enforcement_state().last_holder_commitment -= 1;
7545 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7546 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7549 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7550 &msgs::RevokeAndACK {
7552 per_commitment_secret,
7553 next_per_commitment_point,
7555 next_local_nonce: None,
7557 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7558 check_added_monitors!(nodes[1], 1);
7559 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7563 fn test_bump_txn_sanitize_tracking_maps() {
7564 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7565 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7567 let chanmon_cfgs = create_chanmon_cfgs(2);
7568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7570 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7572 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7573 // Lock HTLC in both directions
7574 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7575 let (_, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7577 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7578 assert_eq!(revoked_local_txn[0].input.len(), 1);
7579 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7581 // Revoke local commitment tx
7582 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7584 // Broadcast set of revoked txn on A
7585 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7586 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7587 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7589 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7590 check_closed_broadcast!(nodes[0], true);
7591 check_added_monitors!(nodes[0], 1);
7592 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7594 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7595 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7596 check_spends!(node_txn[0], revoked_local_txn[0]);
7597 check_spends!(node_txn[1], revoked_local_txn[0]);
7598 check_spends!(node_txn[2], revoked_local_txn[0]);
7599 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7603 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7604 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7606 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7607 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7608 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7613 fn test_channel_conf_timeout() {
7614 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7615 // confirm within 2016 blocks, as recommended by BOLT 2.
7616 let chanmon_cfgs = create_chanmon_cfgs(2);
7617 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7618 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7619 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7621 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7623 // The outbound node should wait forever for confirmation:
7624 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7625 // copied here instead of directly referencing the constant.
7626 connect_blocks(&nodes[0], 2016);
7627 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7629 // The inbound node should fail the channel after exactly 2016 blocks
7630 connect_blocks(&nodes[1], 2015);
7631 check_added_monitors!(nodes[1], 0);
7632 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7634 connect_blocks(&nodes[1], 1);
7635 check_added_monitors!(nodes[1], 1);
7636 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
7637 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7638 assert_eq!(close_ev.len(), 1);
7640 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
7641 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7642 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7644 _ => panic!("Unexpected event"),
7649 fn test_override_channel_config() {
7650 let chanmon_cfgs = create_chanmon_cfgs(2);
7651 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7652 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7653 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7655 // Node0 initiates a channel to node1 using the override config.
7656 let mut override_config = UserConfig::default();
7657 override_config.channel_handshake_config.our_to_self_delay = 200;
7659 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7661 // Assert the channel created by node0 is using the override config.
7662 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7663 assert_eq!(res.channel_flags, 0);
7664 assert_eq!(res.to_self_delay, 200);
7668 fn test_override_0msat_htlc_minimum() {
7669 let mut zero_config = UserConfig::default();
7670 zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7671 let chanmon_cfgs = create_chanmon_cfgs(2);
7672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7674 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7676 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7677 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7678 assert_eq!(res.htlc_minimum_msat, 1);
7680 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7681 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7682 assert_eq!(res.htlc_minimum_msat, 1);
7686 fn test_channel_update_has_correct_htlc_maximum_msat() {
7687 // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7688 // Bolt 7 specifies that if present `htlc_maximum_msat`:
7689 // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7690 // 90% of the `channel_value`.
7691 // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7693 let mut config_30_percent = UserConfig::default();
7694 config_30_percent.channel_handshake_config.announced_channel = true;
7695 config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7696 let mut config_50_percent = UserConfig::default();
7697 config_50_percent.channel_handshake_config.announced_channel = true;
7698 config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7699 let mut config_95_percent = UserConfig::default();
7700 config_95_percent.channel_handshake_config.announced_channel = true;
7701 config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7702 let mut config_100_percent = UserConfig::default();
7703 config_100_percent.channel_handshake_config.announced_channel = true;
7704 config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7706 let chanmon_cfgs = create_chanmon_cfgs(4);
7707 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7708 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)]);
7709 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7711 let channel_value_satoshis = 100000;
7712 let channel_value_msat = channel_value_satoshis * 1000;
7713 let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7714 let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7715 let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7717 let (node_0_chan_update, node_1_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7718 let (node_2_chan_update, node_3_chan_update, _, _) = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7720 // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7721 // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7722 assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7723 // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7724 // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7725 assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7727 // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7728 // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7730 assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7731 // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7732 // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7734 assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7738 fn test_manually_accept_inbound_channel_request() {
7739 let mut manually_accept_conf = UserConfig::default();
7740 manually_accept_conf.manually_accept_inbound_channels = true;
7741 let chanmon_cfgs = create_chanmon_cfgs(2);
7742 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7743 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7744 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7746 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7747 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7749 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7751 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7752 // accepting the inbound channel request.
7753 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7755 let events = nodes[1].node.get_and_clear_pending_events();
7757 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7758 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
7760 _ => panic!("Unexpected event"),
7763 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7764 assert_eq!(accept_msg_ev.len(), 1);
7766 match accept_msg_ev[0] {
7767 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7768 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7770 _ => panic!("Unexpected event"),
7773 nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7775 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7776 assert_eq!(close_msg_ev.len(), 1);
7778 let events = nodes[1].node.get_and_clear_pending_events();
7780 Event::ChannelClosed { user_channel_id, .. } => {
7781 assert_eq!(user_channel_id, 23);
7783 _ => panic!("Unexpected event"),
7788 fn test_manually_reject_inbound_channel_request() {
7789 let mut manually_accept_conf = UserConfig::default();
7790 manually_accept_conf.manually_accept_inbound_channels = true;
7791 let chanmon_cfgs = create_chanmon_cfgs(2);
7792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7794 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7796 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7797 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7799 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7801 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7802 // rejecting the inbound channel request.
7803 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7805 let events = nodes[1].node.get_and_clear_pending_events();
7807 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7808 nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
7810 _ => panic!("Unexpected event"),
7813 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7814 assert_eq!(close_msg_ev.len(), 1);
7816 match close_msg_ev[0] {
7817 MessageSendEvent::HandleError { ref node_id, .. } => {
7818 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7820 _ => panic!("Unexpected event"),
7822 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
7826 fn test_reject_funding_before_inbound_channel_accepted() {
7827 // This tests that when `UserConfig::manually_accept_inbound_channels` is set to true, inbound
7828 // channels must to be manually accepted through `ChannelManager::accept_inbound_channel` by
7829 // the node operator before the counterparty sends a `FundingCreated` message. If a
7830 // `FundingCreated` message is received before the channel is accepted, it should be rejected
7831 // and the channel should be closed.
7832 let mut manually_accept_conf = UserConfig::default();
7833 manually_accept_conf.manually_accept_inbound_channels = true;
7834 let chanmon_cfgs = create_chanmon_cfgs(2);
7835 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7836 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7837 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7839 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7840 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7841 let temp_channel_id = res.temporary_channel_id;
7843 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7845 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in the `msg_events`.
7846 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7848 // Clear the `Event::OpenChannelRequest` event without responding to the request.
7849 nodes[1].node.get_and_clear_pending_events();
7851 // Get the `AcceptChannel` message of `nodes[1]` without calling
7852 // `ChannelManager::accept_inbound_channel`, which generates a
7853 // `MessageSendEvent::SendAcceptChannel` event. The message is passed to `nodes[0]`
7854 // `handle_accept_channel`, which is required in order for `create_funding_transaction` to
7855 // succeed when `nodes[0]` is passed to it.
7856 let accept_chan_msg = {
7857 let mut node_1_per_peer_lock;
7858 let mut node_1_peer_state_lock;
7859 let channel = get_channel_ref!(&nodes[1], nodes[0], node_1_per_peer_lock, node_1_peer_state_lock, temp_channel_id);
7860 channel.get_accept_channel_message()
7862 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
7864 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
7866 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
7867 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
7869 // The `funding_created_msg` should be rejected by `nodes[1]` as it hasn't accepted the channel
7870 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
7872 let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7873 assert_eq!(close_msg_ev.len(), 1);
7875 let expected_err = "FundingCreated message received before the channel was accepted";
7876 match close_msg_ev[0] {
7877 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id, } => {
7878 assert_eq!(msg.channel_id, temp_channel_id);
7879 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7880 assert_eq!(msg.data, expected_err);
7882 _ => panic!("Unexpected event"),
7885 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
7889 fn test_can_not_accept_inbound_channel_twice() {
7890 let mut manually_accept_conf = UserConfig::default();
7891 manually_accept_conf.manually_accept_inbound_channels = true;
7892 let chanmon_cfgs = create_chanmon_cfgs(2);
7893 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7894 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
7895 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7897 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, Some(manually_accept_conf)).unwrap();
7898 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7900 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7902 // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
7903 // accepting the inbound channel request.
7904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
7906 let events = nodes[1].node.get_and_clear_pending_events();
7908 Event::OpenChannelRequest { temporary_channel_id, .. } => {
7909 nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
7910 let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
7912 Err(APIError::APIMisuseError { err }) => {
7913 assert_eq!(err, "The channel isn't currently awaiting to be accepted.");
7915 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
7916 Err(_) => panic!("Unexpected Error"),
7919 _ => panic!("Unexpected event"),
7922 // Ensure that the channel wasn't closed after attempting to accept it twice.
7923 let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
7924 assert_eq!(accept_msg_ev.len(), 1);
7926 match accept_msg_ev[0] {
7927 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
7928 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7930 _ => panic!("Unexpected event"),
7935 fn test_can_not_accept_unknown_inbound_channel() {
7936 let chanmon_cfg = create_chanmon_cfgs(2);
7937 let node_cfg = create_node_cfgs(2, &chanmon_cfg);
7938 let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
7939 let nodes = create_network(2, &node_cfg, &node_chanmgr);
7941 let unknown_channel_id = [0; 32];
7942 let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
7944 Err(APIError::ChannelUnavailable { err }) => {
7945 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()));
7947 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
7948 Err(_) => panic!("Unexpected Error"),
7953 fn test_onion_value_mpp_set_calculation() {
7954 // Test that we use the onion value `amt_to_forward` when
7955 // calculating whether we've reached the `total_msat` of an MPP
7956 // by having a routing node forward more than `amt_to_forward`
7957 // and checking that the receiving node doesn't generate
7958 // a PaymentClaimable event too early
7960 let chanmon_cfgs = create_chanmon_cfgs(node_count);
7961 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
7962 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
7963 let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
7965 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
7966 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
7967 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
7968 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
7970 let total_msat = 100_000;
7971 let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
7972 let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
7973 let sample_path = route.paths.pop().unwrap();
7975 let mut path_1 = sample_path.clone();
7976 path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
7977 path_1.hops[0].short_channel_id = chan_1_id;
7978 path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
7979 path_1.hops[1].short_channel_id = chan_3_id;
7980 path_1.hops[1].fee_msat = 100_000;
7981 route.paths.push(path_1);
7983 let mut path_2 = sample_path.clone();
7984 path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
7985 path_2.hops[0].short_channel_id = chan_2_id;
7986 path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
7987 path_2.hops[1].short_channel_id = chan_4_id;
7988 path_2.hops[1].fee_msat = 1_000;
7989 route.paths.push(path_2);
7992 let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
7993 let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
7994 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
7995 nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
7996 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
7997 check_added_monitors!(nodes[0], expected_paths.len());
7999 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8000 assert_eq!(events.len(), expected_paths.len());
8003 let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8004 let mut payment_event = SendEvent::from_event(ev);
8005 let mut prev_node = &nodes[0];
8007 for (idx, &node) in expected_paths[0].iter().enumerate() {
8008 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8010 if idx == 0 { // routing node
8011 let session_priv = [3; 32];
8012 let height = nodes[0].best_block_info().1;
8013 let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8014 let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8015 let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8016 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8017 // Edit amt_to_forward to simulate the sender having set
8018 // the final amount and the routing node taking less fee
8019 onion_payloads[1].amt_to_forward = 99_000;
8020 let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8021 payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8024 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8025 check_added_monitors!(node, 0);
8026 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8027 expect_pending_htlcs_forwardable!(node);
8030 let mut events_2 = node.node.get_and_clear_pending_msg_events();
8031 assert_eq!(events_2.len(), 1);
8032 check_added_monitors!(node, 1);
8033 payment_event = SendEvent::from_event(events_2.remove(0));
8034 assert_eq!(payment_event.msgs.len(), 1);
8036 let events_2 = node.node.get_and_clear_pending_events();
8037 assert!(events_2.is_empty());
8044 let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8045 pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8047 claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8050 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8052 let routing_node_count = msat_amounts.len();
8053 let node_count = routing_node_count + 2;
8055 let chanmon_cfgs = create_chanmon_cfgs(node_count);
8056 let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8057 let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8058 let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8063 // Create channels for each amount
8064 let mut expected_paths = Vec::with_capacity(routing_node_count);
8065 let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8066 let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8067 for i in 0..routing_node_count {
8068 let routing_node = 2 + i;
8069 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8070 src_chan_ids.push(src_chan_id);
8071 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8072 dst_chan_ids.push(dst_chan_id);
8073 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8074 expected_paths.push(path);
8076 let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8078 // Create a route for each amount
8079 let example_amount = 100000;
8080 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);
8081 let sample_path = route.paths.pop().unwrap();
8082 for i in 0..routing_node_count {
8083 let routing_node = 2 + i;
8084 let mut path = sample_path.clone();
8085 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8086 path.hops[0].short_channel_id = src_chan_ids[i];
8087 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8088 path.hops[1].short_channel_id = dst_chan_ids[i];
8089 path.hops[1].fee_msat = msat_amounts[i];
8090 route.paths.push(path);
8093 // Send payment with manually set total_msat
8094 let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8095 let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8096 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8097 nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8098 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8099 check_added_monitors!(nodes[src_idx], expected_paths.len());
8101 let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8102 assert_eq!(events.len(), expected_paths.len());
8103 let mut amount_received = 0;
8104 for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8105 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8107 let current_path_amount = msat_amounts[path_idx];
8108 amount_received += current_path_amount;
8109 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8110 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8113 claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8117 fn test_overshoot_mpp() {
8118 do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8119 do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8123 fn test_simple_mpp() {
8124 // Simple test of sending a multi-path payment.
8125 let chanmon_cfgs = create_chanmon_cfgs(4);
8126 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8127 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8128 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8130 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8131 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8132 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8133 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8135 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8136 let path = route.paths[0].clone();
8137 route.paths.push(path);
8138 route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8139 route.paths[0].hops[0].short_channel_id = chan_1_id;
8140 route.paths[0].hops[1].short_channel_id = chan_3_id;
8141 route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8142 route.paths[1].hops[0].short_channel_id = chan_2_id;
8143 route.paths[1].hops[1].short_channel_id = chan_4_id;
8144 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8145 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8149 fn test_preimage_storage() {
8150 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8151 let chanmon_cfgs = create_chanmon_cfgs(2);
8152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8156 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8159 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8160 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8161 nodes[0].node.send_payment_with_route(&route, payment_hash,
8162 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8163 check_added_monitors!(nodes[0], 1);
8164 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8165 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8166 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8167 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8169 // Note that after leaving the above scope we have no knowledge of any arguments or return
8170 // values from previous calls.
8171 expect_pending_htlcs_forwardable!(nodes[1]);
8172 let events = nodes[1].node.get_and_clear_pending_events();
8173 assert_eq!(events.len(), 1);
8175 Event::PaymentClaimable { ref purpose, .. } => {
8177 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8178 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8180 _ => panic!("expected PaymentPurpose::InvoicePayment")
8183 _ => panic!("Unexpected event"),
8188 #[allow(deprecated)]
8189 fn test_secret_timeout() {
8190 // Simple test of payment secret storage time outs. After
8191 // `create_inbound_payment(_for_hash)_legacy` is removed, this test will be removed as well.
8192 let chanmon_cfgs = create_chanmon_cfgs(2);
8193 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8194 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8195 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8197 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8199 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment_legacy(Some(100_000), 2).unwrap();
8201 // We should fail to register the same payment hash twice, at least until we've connected a
8202 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8203 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8204 assert_eq!(err, "Duplicate payment hash");
8205 } else { panic!(); }
8207 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8208 create_dummy_block(node_1_blocks.last().unwrap().0.block_hash(), node_1_blocks.len() as u32 + 7200, Vec::new())
8210 connect_block(&nodes[1], &block);
8211 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2) {
8212 assert_eq!(err, "Duplicate payment hash");
8213 } else { panic!(); }
8215 // If we then connect the second block, we should be able to register the same payment hash
8216 // again (this time getting a new payment secret).
8217 block.header.prev_blockhash = block.header.block_hash();
8218 block.header.time += 1;
8219 connect_block(&nodes[1], &block);
8220 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash_legacy(payment_hash, Some(100_000), 2).unwrap();
8221 assert_ne!(payment_secret_1, our_payment_secret);
8224 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8225 nodes[0].node.send_payment_with_route(&route, payment_hash,
8226 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(payment_hash.0)).unwrap();
8227 check_added_monitors!(nodes[0], 1);
8228 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8229 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8230 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8231 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8233 // Note that after leaving the above scope we have no knowledge of any arguments or return
8234 // values from previous calls.
8235 expect_pending_htlcs_forwardable!(nodes[1]);
8236 let events = nodes[1].node.get_and_clear_pending_events();
8237 assert_eq!(events.len(), 1);
8239 Event::PaymentClaimable { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8240 assert!(payment_preimage.is_none());
8241 assert_eq!(payment_secret, our_payment_secret);
8242 // We don't actually have the payment preimage with which to claim this payment!
8244 _ => panic!("Unexpected event"),
8249 fn test_bad_secret_hash() {
8250 // Simple test of unregistered payment hash/invalid payment secret handling
8251 let chanmon_cfgs = create_chanmon_cfgs(2);
8252 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8253 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8254 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8256 create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8258 let random_payment_hash = PaymentHash([42; 32]);
8259 let random_payment_secret = PaymentSecret([43; 32]);
8260 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8261 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8263 // All the below cases should end up being handled exactly identically, so we macro the
8264 // resulting events.
8265 macro_rules! handle_unknown_invalid_payment_data {
8266 ($payment_hash: expr) => {
8267 check_added_monitors!(nodes[0], 1);
8268 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8269 let payment_event = SendEvent::from_event(events.pop().unwrap());
8270 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8271 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8273 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8274 // again to process the pending backwards-failure of the HTLC
8275 expect_pending_htlcs_forwardable!(nodes[1]);
8276 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8277 check_added_monitors!(nodes[1], 1);
8279 // We should fail the payment back
8280 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8281 match events.pop().unwrap() {
8282 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8283 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8284 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8286 _ => panic!("Unexpected event"),
8291 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8292 // Error data is the HTLC value (100,000) and current block height
8293 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8295 // Send a payment with the right payment hash but the wrong payment secret
8296 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8297 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8298 handle_unknown_invalid_payment_data!(our_payment_hash);
8299 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8301 // Send a payment with a random payment hash, but the right payment secret
8302 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8303 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8304 handle_unknown_invalid_payment_data!(random_payment_hash);
8305 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8307 // Send a payment with a random payment hash and random payment secret
8308 nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8309 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8310 handle_unknown_invalid_payment_data!(random_payment_hash);
8311 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8315 fn test_update_err_monitor_lockdown() {
8316 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8317 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8318 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8321 // This scenario may happen in a watchtower setup, where watchtower process a block height
8322 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8323 // commitment at same time.
8325 let chanmon_cfgs = create_chanmon_cfgs(2);
8326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8328 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8330 // Create some initial channel
8331 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8332 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8334 // Rebalance the network to generate htlc in the two directions
8335 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8337 // Route a HTLC from node 0 to node 1 (but don't settle)
8338 let (preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8340 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8341 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8342 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8343 let persister = test_utils::TestPersister::new();
8346 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8347 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8348 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8349 assert!(new_monitor == *monitor);
8352 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);
8353 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8356 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8357 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8358 // transaction lock time requirements here.
8359 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8360 watchtower.chain_monitor.block_connected(&block, 200);
8362 // Try to update ChannelMonitor
8363 nodes[1].node.claim_funds(preimage);
8364 check_added_monitors!(nodes[1], 1);
8365 expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8367 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8368 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8369 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8371 let mut node_0_per_peer_lock;
8372 let mut node_0_peer_state_lock;
8373 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8374 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8375 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8376 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8377 } else { assert!(false); }
8379 // Our local monitor is in-sync and hasn't processed yet timeout
8380 check_added_monitors!(nodes[0], 1);
8381 let events = nodes[0].node.get_and_clear_pending_events();
8382 assert_eq!(events.len(), 1);
8386 fn test_concurrent_monitor_claim() {
8387 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8388 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8389 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8390 // state N+1 confirms. Alice claims output from state N+1.
8392 let chanmon_cfgs = create_chanmon_cfgs(2);
8393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8395 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8397 // Create some initial channel
8398 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8399 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8401 // Rebalance the network to generate htlc in the two directions
8402 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8404 // Route a HTLC from node 0 to node 1 (but don't settle)
8405 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8407 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8408 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8409 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8410 let persister = test_utils::TestPersister::new();
8411 let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8412 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8414 let watchtower_alice = {
8416 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8417 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8418 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8419 assert!(new_monitor == *monitor);
8422 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8423 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8426 let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8427 // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8428 // requirements here.
8429 const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8430 alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8431 watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8433 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8435 let mut txn = alice_broadcaster.txn_broadcast();
8436 assert_eq!(txn.len(), 2);
8440 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8441 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8442 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8443 let persister = test_utils::TestPersister::new();
8444 let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8445 let watchtower_bob = {
8447 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8448 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8449 &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8450 assert!(new_monitor == *monitor);
8453 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8454 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), ChannelMonitorUpdateStatus::Completed);
8457 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8459 // Route another payment to generate another update with still previous HTLC pending
8460 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8461 nodes[1].node.send_payment_with_route(&route, payment_hash,
8462 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8463 check_added_monitors!(nodes[1], 1);
8465 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8466 assert_eq!(updates.update_add_htlcs.len(), 1);
8467 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8469 let mut node_0_per_peer_lock;
8470 let mut node_0_peer_state_lock;
8471 let mut channel = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2);
8472 if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8473 // Watchtower Alice should already have seen the block and reject the update
8474 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::PermanentFailure);
8475 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8476 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8477 } else { assert!(false); }
8479 // Our local monitor is in-sync and hasn't processed yet timeout
8480 check_added_monitors!(nodes[0], 1);
8482 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8483 watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8485 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8488 let mut txn = bob_broadcaster.txn_broadcast();
8489 assert_eq!(txn.len(), 2);
8490 bob_state_y = txn.remove(0);
8493 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8494 let height = HTLC_TIMEOUT_BROADCAST + 1;
8495 connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8496 check_closed_broadcast(&nodes[0], 1, true);
8497 check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false);
8498 watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8499 check_added_monitors(&nodes[0], 1);
8501 let htlc_txn = alice_broadcaster.txn_broadcast();
8502 assert_eq!(htlc_txn.len(), 2);
8503 check_spends!(htlc_txn[0], bob_state_y);
8504 // Alice doesn't clean up the old HTLC claim since it hasn't seen a conflicting spend for
8505 // it. However, she should, because it now has an invalid parent.
8506 check_spends!(htlc_txn[1], alice_state);
8511 fn test_pre_lockin_no_chan_closed_update() {
8512 // Test that if a peer closes a channel in response to a funding_created message we don't
8513 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8516 // Doing so would imply a channel monitor update before the initial channel monitor
8517 // registration, violating our API guarantees.
8519 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8520 // then opening a second channel with the same funding output as the first (which is not
8521 // rejected because the first channel does not exist in the ChannelManager) and closing it
8522 // before receiving funding_signed.
8523 let chanmon_cfgs = create_chanmon_cfgs(2);
8524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8528 // Create an initial channel
8529 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8530 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8531 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8532 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8533 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8535 // Move the first channel through the funding flow...
8536 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8538 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8539 check_added_monitors!(nodes[0], 0);
8541 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8542 let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8543 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8544 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8545 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true);
8549 fn test_htlc_no_detection() {
8550 // This test is a mutation to underscore the detection logic bug we had
8551 // before #653. HTLC value routed is above the remaining balance, thus
8552 // inverting HTLC and `to_remote` output. HTLC will come second and
8553 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8554 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8555 // outputs order detection for correct spending children filtring.
8557 let chanmon_cfgs = create_chanmon_cfgs(2);
8558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8560 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8562 // Create some initial channels
8563 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8565 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8566 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8567 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8568 assert_eq!(local_txn[0].input.len(), 1);
8569 assert_eq!(local_txn[0].output.len(), 3);
8570 check_spends!(local_txn[0], chan_1.3);
8572 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8573 let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8574 connect_block(&nodes[0], &block);
8575 // We deliberately connect the local tx twice as this should provoke a failure calling
8576 // this test before #653 fix.
8577 chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8578 check_closed_broadcast!(nodes[0], true);
8579 check_added_monitors!(nodes[0], 1);
8580 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8581 connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8583 let htlc_timeout = {
8584 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8585 assert_eq!(node_txn.len(), 1);
8586 assert_eq!(node_txn[0].input.len(), 1);
8587 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8588 check_spends!(node_txn[0], local_txn[0]);
8592 connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8593 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8594 expect_payment_failed!(nodes[0], our_payment_hash, false);
8597 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8598 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8599 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8600 // Carol, Alice would be the upstream node, and Carol the downstream.)
8602 // Steps of the test:
8603 // 1) Alice sends a HTLC to Carol through Bob.
8604 // 2) Carol doesn't settle the HTLC.
8605 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8606 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8607 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8608 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8609 // 5) Carol release the preimage to Bob off-chain.
8610 // 6) Bob claims the offered output on the broadcasted commitment.
8611 let chanmon_cfgs = create_chanmon_cfgs(3);
8612 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8613 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8614 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8616 // Create some initial channels
8617 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8618 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8620 // Steps (1) and (2):
8621 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8622 let (payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8624 // Check that Alice's commitment transaction now contains an output for this HTLC.
8625 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8626 check_spends!(alice_txn[0], chan_ab.3);
8627 assert_eq!(alice_txn[0].output.len(), 2);
8628 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8629 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8630 assert_eq!(alice_txn.len(), 2);
8632 // Steps (3) and (4):
8633 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8634 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8635 let mut force_closing_node = 0; // Alice force-closes
8636 let mut counterparty_node = 1; // Bob if Alice force-closes
8639 if !broadcast_alice {
8640 force_closing_node = 1;
8641 counterparty_node = 0;
8643 nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8644 check_closed_broadcast!(nodes[force_closing_node], true);
8645 check_added_monitors!(nodes[force_closing_node], 1);
8646 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8647 if go_onchain_before_fulfill {
8648 let txn_to_broadcast = match broadcast_alice {
8649 true => alice_txn.clone(),
8650 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8652 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8653 if broadcast_alice {
8654 check_closed_broadcast!(nodes[1], true);
8655 check_added_monitors!(nodes[1], 1);
8656 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8661 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8662 // process of removing the HTLC from their commitment transactions.
8663 nodes[2].node.claim_funds(payment_preimage);
8664 check_added_monitors!(nodes[2], 1);
8665 expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8667 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8668 assert!(carol_updates.update_add_htlcs.is_empty());
8669 assert!(carol_updates.update_fail_htlcs.is_empty());
8670 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8671 assert!(carol_updates.update_fee.is_none());
8672 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8674 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8675 expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false, false);
8676 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8677 if !go_onchain_before_fulfill && broadcast_alice {
8678 let events = nodes[1].node.get_and_clear_pending_msg_events();
8679 assert_eq!(events.len(), 1);
8681 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8682 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8684 _ => panic!("Unexpected event"),
8687 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8688 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8689 // Carol<->Bob's updated commitment transaction info.
8690 check_added_monitors!(nodes[1], 2);
8692 let events = nodes[1].node.get_and_clear_pending_msg_events();
8693 assert_eq!(events.len(), 2);
8694 let bob_revocation = match events[0] {
8695 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8696 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8699 _ => panic!("Unexpected event"),
8701 let bob_updates = match events[1] {
8702 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8703 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8706 _ => panic!("Unexpected event"),
8709 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8710 check_added_monitors!(nodes[2], 1);
8711 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8712 check_added_monitors!(nodes[2], 1);
8714 let events = nodes[2].node.get_and_clear_pending_msg_events();
8715 assert_eq!(events.len(), 1);
8716 let carol_revocation = match events[0] {
8717 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8718 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8721 _ => panic!("Unexpected event"),
8723 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8724 check_added_monitors!(nodes[1], 1);
8726 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8727 // here's where we put said channel's commitment tx on-chain.
8728 let mut txn_to_broadcast = alice_txn.clone();
8729 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8730 if !go_onchain_before_fulfill {
8731 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8732 // If Bob was the one to force-close, he will have already passed these checks earlier.
8733 if broadcast_alice {
8734 check_closed_broadcast!(nodes[1], true);
8735 check_added_monitors!(nodes[1], 1);
8736 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8738 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8739 if broadcast_alice {
8740 assert_eq!(bob_txn.len(), 1);
8741 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8743 assert_eq!(bob_txn.len(), 2);
8744 check_spends!(bob_txn[0], chan_ab.3);
8749 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8750 // broadcasted commitment transaction.
8752 let script_weight = match broadcast_alice {
8753 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8754 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8756 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8757 // Bob force-closed and broadcasts the commitment transaction along with a
8758 // HTLC-output-claiming transaction.
8759 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8760 if broadcast_alice {
8761 assert_eq!(bob_txn.len(), 1);
8762 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8763 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8765 assert_eq!(bob_txn.len(), 2);
8766 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8767 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8773 fn test_onchain_htlc_settlement_after_close() {
8774 do_test_onchain_htlc_settlement_after_close(true, true);
8775 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8776 do_test_onchain_htlc_settlement_after_close(true, false);
8777 do_test_onchain_htlc_settlement_after_close(false, false);
8781 fn test_duplicate_temporary_channel_id_from_different_peers() {
8782 // Tests that we can accept two different `OpenChannel` requests with the same
8783 // `temporary_channel_id`, as long as they are from different peers.
8784 let chanmon_cfgs = create_chanmon_cfgs(3);
8785 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8786 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8787 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8789 // Create an first channel channel
8790 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8791 let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8793 // Create an second channel
8794 nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None).unwrap();
8795 let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8797 // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8798 // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8799 open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8801 // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8802 // `temporary_channel_id` as they are from different peers.
8803 nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8805 let events = nodes[0].node.get_and_clear_pending_msg_events();
8806 assert_eq!(events.len(), 1);
8808 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8809 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8810 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8812 _ => panic!("Unexpected event"),
8816 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8818 let events = nodes[0].node.get_and_clear_pending_msg_events();
8819 assert_eq!(events.len(), 1);
8821 MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8822 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8823 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8825 _ => panic!("Unexpected event"),
8831 fn test_duplicate_chan_id() {
8832 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8833 // already open we reject it and keep the old channel.
8835 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8836 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8837 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8838 // updating logic for the existing channel.
8839 let chanmon_cfgs = create_chanmon_cfgs(2);
8840 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8841 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8842 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8844 // Create an initial channel
8845 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8846 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8847 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8848 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()));
8850 // Try to create a second channel with the same temporary_channel_id as the first and check
8851 // that it is rejected.
8852 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8854 let events = nodes[1].node.get_and_clear_pending_msg_events();
8855 assert_eq!(events.len(), 1);
8857 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8858 // Technically, at this point, nodes[1] would be justified in thinking both the
8859 // first (valid) and second (invalid) channels are closed, given they both have
8860 // the same non-temporary channel_id. However, currently we do not, so we just
8861 // move forward with it.
8862 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8863 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8865 _ => panic!("Unexpected event"),
8869 // Move the first channel through the funding flow...
8870 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8872 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8873 check_added_monitors!(nodes[0], 0);
8875 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8876 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8878 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8879 assert_eq!(added_monitors.len(), 1);
8880 assert_eq!(added_monitors[0].0, funding_output);
8881 added_monitors.clear();
8883 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
8885 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8887 let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8888 let channel_id = funding_outpoint.to_channel_id();
8890 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8893 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8894 // Technically this is allowed by the spec, but we don't support it and there's little reason
8895 // to. Still, it shouldn't cause any other issues.
8896 open_chan_msg.temporary_channel_id = channel_id;
8897 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8899 let events = nodes[1].node.get_and_clear_pending_msg_events();
8900 assert_eq!(events.len(), 1);
8902 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8903 // Technically, at this point, nodes[1] would be justified in thinking both
8904 // channels are closed, but currently we do not, so we just move forward with it.
8905 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8906 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8908 _ => panic!("Unexpected event"),
8912 // Now try to create a second channel which has a duplicate funding output.
8913 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8914 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8915 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
8916 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()));
8917 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
8919 let funding_created = {
8920 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
8921 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
8922 // Once we call `get_outbound_funding_created` the channel has a duplicate channel_id as
8923 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
8924 // try to create another channel. Instead, we drop the channel entirely here (leaving the
8925 // channelmanager in a possibly nonsense state instead).
8926 let mut as_chan = a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap();
8927 let logger = test_utils::TestLogger::new();
8928 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8930 check_added_monitors!(nodes[0], 0);
8931 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8932 // At this point we'll look up if the channel_id is present and immediately fail the channel
8933 // without trying to persist the `ChannelMonitor`.
8934 check_added_monitors!(nodes[1], 0);
8936 // ...still, nodes[1] will reject the duplicate channel.
8938 let events = nodes[1].node.get_and_clear_pending_msg_events();
8939 assert_eq!(events.len(), 1);
8941 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8942 // Technically, at this point, nodes[1] would be justified in thinking both
8943 // channels are closed, but currently we do not, so we just move forward with it.
8944 assert_eq!(msg.channel_id, channel_id);
8945 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8947 _ => panic!("Unexpected event"),
8951 // finally, finish creating the original channel and send a payment over it to make sure
8952 // everything is functional.
8953 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8955 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8956 assert_eq!(added_monitors.len(), 1);
8957 assert_eq!(added_monitors[0].0, funding_output);
8958 added_monitors.clear();
8960 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
8962 let events_4 = nodes[0].node.get_and_clear_pending_events();
8963 assert_eq!(events_4.len(), 0);
8964 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8965 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8967 let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8968 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
8969 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8971 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8975 fn test_error_chans_closed() {
8976 // Test that we properly handle error messages, closing appropriate channels.
8978 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8979 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8980 // we can test various edge cases around it to ensure we don't regress.
8981 let chanmon_cfgs = create_chanmon_cfgs(3);
8982 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8983 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8984 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8986 // Create some initial channels
8987 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8988 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8989 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
8991 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8992 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8993 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8995 // Closing a channel from a different peer has no effect
8996 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8997 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8999 // Closing one channel doesn't impact others
9000 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9001 check_added_monitors!(nodes[0], 1);
9002 check_closed_broadcast!(nodes[0], false);
9003 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9004 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9005 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9006 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);
9007 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);
9009 // A null channel ID should close all channels
9010 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9011 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9012 check_added_monitors!(nodes[0], 2);
9013 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) });
9014 let events = nodes[0].node.get_and_clear_pending_msg_events();
9015 assert_eq!(events.len(), 2);
9017 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9018 assert_eq!(msg.contents.flags & 2, 2);
9020 _ => panic!("Unexpected event"),
9023 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9024 assert_eq!(msg.contents.flags & 2, 2);
9026 _ => panic!("Unexpected event"),
9028 // Note that at this point users of a standard PeerHandler will end up calling
9029 // peer_disconnected.
9030 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9031 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9033 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9034 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9035 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9039 fn test_invalid_funding_tx() {
9040 // Test that we properly handle invalid funding transactions sent to us from a peer.
9042 // Previously, all other major lightning implementations had failed to properly sanitize
9043 // funding transactions from their counterparties, leading to a multi-implementation critical
9044 // security vulnerability (though we always sanitized properly, we've previously had
9045 // un-released crashes in the sanitization process).
9047 // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9048 // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9049 // gave up on it. We test this here by generating such a transaction.
9050 let chanmon_cfgs = create_chanmon_cfgs(2);
9051 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9052 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9053 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9055 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9056 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()));
9057 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()));
9059 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9061 // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9062 // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9063 // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9065 let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9066 let wit_program_script: Script = wit_program.into();
9067 for output in tx.output.iter_mut() {
9068 // Make the confirmed funding transaction have a bogus script_pubkey
9069 output.script_pubkey = Script::new_v0_p2wsh(&wit_program_script.wscript_hash());
9072 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9073 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()));
9074 check_added_monitors!(nodes[1], 1);
9075 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9077 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()));
9078 check_added_monitors!(nodes[0], 1);
9079 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9081 let events_1 = nodes[0].node.get_and_clear_pending_events();
9082 assert_eq!(events_1.len(), 0);
9084 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9085 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9086 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9088 let expected_err = "funding tx had wrong script/value or output index";
9089 confirm_transaction_at(&nodes[1], &tx, 1);
9090 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
9091 check_added_monitors!(nodes[1], 1);
9092 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9093 assert_eq!(events_2.len(), 1);
9094 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9095 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9096 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9097 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
9098 } else { panic!(); }
9099 } else { panic!(); }
9100 assert_eq!(nodes[1].node.list_channels().len(), 0);
9102 // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9103 // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9104 // as its not 32 bytes long.
9105 let mut spend_tx = Transaction {
9106 version: 2i32, lock_time: PackedLockTime::ZERO,
9107 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9108 previous_output: BitcoinOutPoint {
9112 script_sig: Script::new(),
9113 sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9114 witness: Witness::from_vec(channelmonitor::deliberately_bogus_accepted_htlc_witness())
9116 output: vec![TxOut {
9118 script_pubkey: Script::new(),
9121 check_spends!(spend_tx, tx);
9122 mine_transaction(&nodes[1], &spend_tx);
9125 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9126 // In the first version of the chain::Confirm interface, after a refactor was made to not
9127 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9128 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9129 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9130 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9131 // spending transaction until height N+1 (or greater). This was due to the way
9132 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9133 // spending transaction at the height the input transaction was confirmed at, not whether we
9134 // should broadcast a spending transaction at the current height.
9135 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9136 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9137 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9138 // until we learned about an additional block.
9140 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9141 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9142 let chanmon_cfgs = create_chanmon_cfgs(3);
9143 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9144 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9145 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9146 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9148 create_announced_chan_between_nodes(&nodes, 0, 1);
9149 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9150 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9151 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9152 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9154 nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9155 check_closed_broadcast!(nodes[1], true);
9156 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9157 check_added_monitors!(nodes[1], 1);
9158 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9159 assert_eq!(node_txn.len(), 1);
9161 let conf_height = nodes[1].best_block_info().1;
9162 if !test_height_before_timelock {
9163 connect_blocks(&nodes[1], 24 * 6);
9165 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9166 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9167 if test_height_before_timelock {
9168 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9169 // generate any events or broadcast any transactions
9170 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9171 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9173 // We should broadcast an HTLC transaction spending our funding transaction first
9174 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9175 assert_eq!(spending_txn.len(), 2);
9176 assert_eq!(spending_txn[0].txid(), node_txn[0].txid());
9177 check_spends!(spending_txn[1], node_txn[0]);
9178 // We should also generate a SpendableOutputs event with the to_self output (as its
9180 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9181 assert_eq!(descriptor_spend_txn.len(), 1);
9183 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9184 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9185 // additional block built on top of the current chain.
9186 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9187 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9188 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 }]);
9189 check_added_monitors!(nodes[1], 1);
9191 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9192 assert!(updates.update_add_htlcs.is_empty());
9193 assert!(updates.update_fulfill_htlcs.is_empty());
9194 assert_eq!(updates.update_fail_htlcs.len(), 1);
9195 assert!(updates.update_fail_malformed_htlcs.is_empty());
9196 assert!(updates.update_fee.is_none());
9197 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9198 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9199 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9204 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9205 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9206 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9209 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9210 let chanmon_cfgs = create_chanmon_cfgs(2);
9211 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9212 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9213 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9215 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9217 let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9218 .with_bolt11_features(nodes[1].node.invoice_features()).unwrap();
9219 let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9221 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9224 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9225 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9226 check_added_monitors!(nodes[0], 1);
9227 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9228 assert_eq!(events.len(), 1);
9229 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9230 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9231 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9233 expect_pending_htlcs_forwardable!(nodes[1]);
9234 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9237 // Note that we use a different PaymentId here to allow us to duplicativly pay
9238 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9239 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9240 check_added_monitors!(nodes[0], 1);
9241 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9242 assert_eq!(events.len(), 1);
9243 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9244 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9245 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9246 // At this point, nodes[1] would notice it has too much value for the payment. It will
9247 // assume the second is a privacy attack (no longer particularly relevant
9248 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9249 // the first HTLC delivered above.
9252 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9253 nodes[1].node.process_pending_htlc_forwards();
9255 if test_for_second_fail_panic {
9256 // Now we go fail back the first HTLC from the user end.
9257 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9259 let expected_destinations = vec![
9260 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9261 HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9263 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], expected_destinations);
9264 nodes[1].node.process_pending_htlc_forwards();
9266 check_added_monitors!(nodes[1], 1);
9267 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9268 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9270 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9271 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9272 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9274 let failure_events = nodes[0].node.get_and_clear_pending_events();
9275 assert_eq!(failure_events.len(), 4);
9276 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9277 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9278 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9279 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9281 // Let the second HTLC fail and claim the first
9282 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9283 nodes[1].node.process_pending_htlc_forwards();
9285 check_added_monitors!(nodes[1], 1);
9286 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9287 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9288 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9290 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9292 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9297 fn test_dup_htlc_second_fail_panic() {
9298 // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9299 // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9300 // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9301 // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9302 do_test_dup_htlc_second_rejected(true);
9306 fn test_dup_htlc_second_rejected() {
9307 // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9308 // simply reject the second HTLC but are still able to claim the first HTLC.
9309 do_test_dup_htlc_second_rejected(false);
9313 fn test_inconsistent_mpp_params() {
9314 // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9315 // such HTLC and allow the second to stay.
9316 let chanmon_cfgs = create_chanmon_cfgs(4);
9317 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9318 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9319 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9321 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9322 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9323 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9324 let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9326 let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9327 .with_bolt11_features(nodes[3].node.invoice_features()).unwrap();
9328 let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9329 assert_eq!(route.paths.len(), 2);
9330 route.paths.sort_by(|path_a, _| {
9331 // Sort the path so that the path through nodes[1] comes first
9332 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9333 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9336 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9338 let cur_height = nodes[0].best_block_info().1;
9339 let payment_id = PaymentId([42; 32]);
9341 let session_privs = {
9342 // We create a fake route here so that we start with three pending HTLCs, which we'll
9343 // ultimately have, just not right away.
9344 let mut dup_route = route.clone();
9345 dup_route.paths.push(route.paths[1].clone());
9346 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9347 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9349 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9350 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9351 &None, session_privs[0]).unwrap();
9352 check_added_monitors!(nodes[0], 1);
9355 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9356 assert_eq!(events.len(), 1);
9357 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9359 assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9361 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9362 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9363 check_added_monitors!(nodes[0], 1);
9366 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9367 assert_eq!(events.len(), 1);
9368 let payment_event = SendEvent::from_event(events.pop().unwrap());
9370 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9371 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9373 expect_pending_htlcs_forwardable!(nodes[2]);
9374 check_added_monitors!(nodes[2], 1);
9376 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9377 assert_eq!(events.len(), 1);
9378 let payment_event = SendEvent::from_event(events.pop().unwrap());
9380 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9381 check_added_monitors!(nodes[3], 0);
9382 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9384 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9385 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9386 // post-payment_secrets) and fail back the new HTLC.
9388 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9389 nodes[3].node.process_pending_htlc_forwards();
9390 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9391 nodes[3].node.process_pending_htlc_forwards();
9393 check_added_monitors!(nodes[3], 1);
9395 let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9396 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9397 commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9399 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 }]);
9400 check_added_monitors!(nodes[2], 1);
9402 let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9403 nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9404 commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9406 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9408 nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9409 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9410 &None, session_privs[2]).unwrap();
9411 check_added_monitors!(nodes[0], 1);
9413 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9414 assert_eq!(events.len(), 1);
9415 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9417 do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9418 expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true);
9422 fn test_keysend_payments_to_public_node() {
9423 let chanmon_cfgs = create_chanmon_cfgs(2);
9424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9426 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9428 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9429 let network_graph = nodes[0].network_graph.clone();
9430 let payer_pubkey = nodes[0].node.get_our_node_id();
9431 let payee_pubkey = nodes[1].node.get_our_node_id();
9432 let route_params = RouteParameters {
9433 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9434 final_value_msat: 10000,
9436 let scorer = test_utils::TestScorer::new();
9437 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9438 let route = find_route(&payer_pubkey, &route_params, &network_graph, None, nodes[0].logger, &scorer, &(), &random_seed_bytes).unwrap();
9440 let test_preimage = PaymentPreimage([42; 32]);
9441 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9442 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9443 check_added_monitors!(nodes[0], 1);
9444 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9445 assert_eq!(events.len(), 1);
9446 let event = events.pop().unwrap();
9447 let path = vec![&nodes[1]];
9448 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9449 claim_payment(&nodes[0], &path, test_preimage);
9453 fn test_keysend_payments_to_private_node() {
9454 let chanmon_cfgs = create_chanmon_cfgs(2);
9455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9457 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9459 let payer_pubkey = nodes[0].node.get_our_node_id();
9460 let payee_pubkey = nodes[1].node.get_our_node_id();
9462 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1]);
9463 let route_params = RouteParameters {
9464 payment_params: PaymentParameters::for_keysend(payee_pubkey, 40),
9465 final_value_msat: 10000,
9467 let network_graph = nodes[0].network_graph.clone();
9468 let first_hops = nodes[0].node.list_usable_channels();
9469 let scorer = test_utils::TestScorer::new();
9470 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
9471 let route = find_route(
9472 &payer_pubkey, &route_params, &network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9473 nodes[0].logger, &scorer, &(), &random_seed_bytes
9476 let test_preimage = PaymentPreimage([42; 32]);
9477 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage),
9478 RecipientOnionFields::spontaneous_empty(), PaymentId(test_preimage.0)).unwrap();
9479 check_added_monitors!(nodes[0], 1);
9480 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9481 assert_eq!(events.len(), 1);
9482 let event = events.pop().unwrap();
9483 let path = vec![&nodes[1]];
9484 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9485 claim_payment(&nodes[0], &path, test_preimage);
9489 fn test_double_partial_claim() {
9490 // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9491 // time out, the sender resends only some of the MPP parts, then the user processes the
9492 // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9494 let chanmon_cfgs = create_chanmon_cfgs(4);
9495 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9496 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9497 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9499 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9500 create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9501 create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9502 create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9504 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9505 assert_eq!(route.paths.len(), 2);
9506 route.paths.sort_by(|path_a, _| {
9507 // Sort the path so that the path through nodes[1] comes first
9508 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9509 core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9512 send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9513 // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9514 // amount of time to respond to.
9516 // Connect some blocks to time out the payment
9517 connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9518 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9520 let failed_destinations = vec![
9521 HTLCDestination::FailedPayment { payment_hash },
9522 HTLCDestination::FailedPayment { payment_hash },
9524 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9526 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9528 // nodes[1] now retries one of the two paths...
9529 nodes[0].node.send_payment_with_route(&route, payment_hash,
9530 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9531 check_added_monitors!(nodes[0], 2);
9533 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9534 assert_eq!(events.len(), 2);
9535 let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9536 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9538 // At this point nodes[3] has received one half of the payment, and the user goes to handle
9539 // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9540 nodes[3].node.claim_funds(payment_preimage);
9541 check_added_monitors!(nodes[3], 0);
9542 assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9545 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9546 #[derive(Clone, Copy, PartialEq)]
9547 enum ExposureEvent {
9548 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9550 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9552 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9553 AtUpdateFeeOutbound,
9556 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9557 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9560 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9561 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9562 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9563 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9564 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9565 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9566 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9567 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9569 let chanmon_cfgs = create_chanmon_cfgs(2);
9570 let mut config = test_default_channel_config();
9571 config.channel_config.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9574 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9576 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9577 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9578 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9579 open_channel.max_accepted_htlcs = 60;
9581 open_channel.dust_limit_satoshis = 546;
9583 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9584 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9585 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9587 let opt_anchors = false;
9589 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9592 let mut node_0_per_peer_lock;
9593 let mut node_0_peer_state_lock;
9594 let mut chan = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id);
9595 chan.holder_dust_limit_satoshis = 546;
9598 nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9599 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()));
9600 check_added_monitors!(nodes[1], 1);
9601 expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9603 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()));
9604 check_added_monitors!(nodes[0], 1);
9605 expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9607 let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9608 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9609 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9611 // Fetch a route in advance as we will be unable to once we're unable to send.
9612 let (mut route, payment_hash, _, payment_secret) =
9613 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9615 let dust_buffer_feerate = {
9616 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9617 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9618 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9619 chan.get_dust_buffer_feerate(None) as u64
9621 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;
9622 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9624 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;
9625 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9627 let dust_htlc_on_counterparty_tx: u64 = 4;
9628 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_config.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9631 if dust_outbound_balance {
9632 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9633 // Outbound dust balance: 4372 sats
9634 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9635 for _ in 0..dust_outbound_htlc_on_holder_tx {
9636 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9637 nodes[0].node.send_payment_with_route(&route, payment_hash,
9638 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9641 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9642 // Inbound dust balance: 4372 sats
9643 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9644 for _ in 0..dust_inbound_htlc_on_holder_tx {
9645 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9649 if dust_outbound_balance {
9650 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9651 // Outbound dust balance: 5000 sats
9652 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9653 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9654 nodes[0].node.send_payment_with_route(&route, payment_hash,
9655 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9658 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9659 // Inbound dust balance: 5000 sats
9660 for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9661 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9666 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9667 route.paths[0].hops.last_mut().unwrap().fee_msat =
9668 if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9669 // With default dust exposure: 5000 sats
9671 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9672 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9673 ), true, APIError::ChannelUnavailable { .. }, {});
9675 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9676 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9677 ), true, APIError::ChannelUnavailable { .. }, {});
9679 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9680 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 });
9681 nodes[1].node.send_payment_with_route(&route, payment_hash,
9682 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9683 check_added_monitors!(nodes[1], 1);
9684 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9685 assert_eq!(events.len(), 1);
9686 let payment_event = SendEvent::from_event(events.remove(0));
9687 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9688 // With default dust exposure: 5000 sats
9690 // Outbound dust balance: 6399 sats
9691 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9692 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9693 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);
9695 // Outbound dust balance: 5200 sats
9696 nodes[0].logger.assert_log("lightning::ln::channel".to_string(),
9697 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9698 dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 1,
9699 config.channel_config.max_dust_htlc_exposure_msat), 1);
9701 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9702 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9703 nodes[0].node.send_payment_with_route(&route, payment_hash,
9704 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9706 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9707 *feerate_lock = *feerate_lock * 10;
9709 nodes[0].node.timer_tick_occurred();
9710 check_added_monitors!(nodes[0], 1);
9711 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9714 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9715 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9716 added_monitors.clear();
9720 fn test_max_dust_htlc_exposure() {
9721 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9722 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9723 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9724 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9725 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9726 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9727 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9728 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9729 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9730 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9731 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9732 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);
9736 fn test_non_final_funding_tx() {
9737 let chanmon_cfgs = create_chanmon_cfgs(2);
9738 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9739 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9740 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9742 let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
9743 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9744 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
9745 let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9746 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
9748 let best_height = nodes[0].node.best_block.read().unwrap().height();
9750 let chan_id = *nodes[0].network_chan_count.borrow();
9751 let events = nodes[0].node.get_and_clear_pending_events();
9752 let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::Script::new(), sequence: Sequence(1), witness: Witness::from_vec(vec!(vec!(1))) };
9753 assert_eq!(events.len(), 1);
9754 let mut tx = match events[0] {
9755 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
9756 // Timelock the transaction _beyond_ the best client height + 1.
9757 Transaction { version: chan_id as i32, lock_time: PackedLockTime(best_height + 2), input: vec![input], output: vec![TxOut {
9758 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
9761 _ => panic!("Unexpected event"),
9763 // Transaction should fail as it's evaluated as non-final for propagation.
9764 match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
9765 Err(APIError::APIMisuseError { err }) => {
9766 assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
9771 // However, transaction should be accepted if it's in a +1 headroom from best block.
9772 tx.lock_time = PackedLockTime(tx.lock_time.0 - 1);
9773 assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
9774 get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9778 fn accept_busted_but_better_fee() {
9779 // If a peer sends us a fee update that is too low, but higher than our previous channel
9780 // feerate, we should accept it. In the future we may want to consider closing the channel
9781 // later, but for now we only accept the update.
9782 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9783 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9784 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9785 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9787 create_chan_between_nodes(&nodes[0], &nodes[1]);
9789 // Set nodes[1] to expect 5,000 sat/kW.
9791 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
9792 *feerate_lock = 5000;
9795 // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
9797 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9798 *feerate_lock = 1000;
9800 nodes[0].node.timer_tick_occurred();
9801 check_added_monitors!(nodes[0], 1);
9803 let events = nodes[0].node.get_and_clear_pending_msg_events();
9804 assert_eq!(events.len(), 1);
9806 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9807 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9808 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9810 _ => panic!("Unexpected event"),
9813 // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
9816 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9817 *feerate_lock = 2000;
9819 nodes[0].node.timer_tick_occurred();
9820 check_added_monitors!(nodes[0], 1);
9822 let events = nodes[0].node.get_and_clear_pending_msg_events();
9823 assert_eq!(events.len(), 1);
9825 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
9826 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9827 commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
9829 _ => panic!("Unexpected event"),
9832 // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
9835 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9836 *feerate_lock = 1000;
9838 nodes[0].node.timer_tick_occurred();
9839 check_added_monitors!(nodes[0], 1);
9841 let events = nodes[0].node.get_and_clear_pending_msg_events();
9842 assert_eq!(events.len(), 1);
9844 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
9845 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
9846 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
9847 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000 (- 250)".to_owned() });
9848 check_closed_broadcast!(nodes[1], true);
9849 check_added_monitors!(nodes[1], 1);
9851 _ => panic!("Unexpected event"),
9855 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
9856 let mut chanmon_cfgs = create_chanmon_cfgs(2);
9857 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9858 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9859 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9860 let min_final_cltv_expiry_delta = 120;
9861 let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
9862 min_final_cltv_expiry_delta - 2 };
9863 let recv_value = 100_000;
9865 create_chan_between_nodes(&nodes[0], &nodes[1]);
9867 let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
9868 let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
9869 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
9870 Some(recv_value), Some(min_final_cltv_expiry_delta));
9871 (payment_hash, payment_preimage, payment_secret)
9873 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
9874 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
9876 let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
9877 nodes[0].node.send_payment_with_route(&route, payment_hash,
9878 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9879 check_added_monitors!(nodes[0], 1);
9880 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9881 assert_eq!(events.len(), 1);
9882 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9883 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9884 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9885 expect_pending_htlcs_forwardable!(nodes[1]);
9888 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
9889 None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
9891 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
9893 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
9895 check_added_monitors!(nodes[1], 1);
9897 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9898 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
9899 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
9901 expect_payment_failed!(nodes[0], payment_hash, true);
9906 fn test_payment_with_custom_min_cltv_expiry_delta() {
9907 do_payment_with_custom_min_final_cltv_expiry(false, false);
9908 do_payment_with_custom_min_final_cltv_expiry(false, true);
9909 do_payment_with_custom_min_final_cltv_expiry(true, false);
9910 do_payment_with_custom_min_final_cltv_expiry(true, true);